0

我不明白是什么机制/触发器导致布局更新。在我创建的简单示例中,按钮的文本在方法内实时更新,但布局直到方法完成后才会更新,即使正确报告了“我应该看到 2 个按钮”。如何获取布局/窗口以将按钮实时添加到布局中?

import sys
import time
from PySide import QtCore, QtGui


class Form(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.button = QtGui.QPushButton("Add")
        self.newButton= QtGui.QPushButton("")
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)
        self.connect(self.button, QtCore.SIGNAL("clicked()"),self.addButton)
        print()

    def addButton(self):
        self.button.setText("Clicked")
        if self.layout.count() > 1:
            self.layout.itemAt(1).widget().deleteLater()
        self.repaint()
        self.layout.update()
        print("I should see " + str(self.layout.count()) + " button(s)")
        time.sleep(3)
        self.layout.addWidget(self.newButton)
        self.repaint()
        self.layout.update()
        print("I should see " + str(self.layout.count()) + " button(s)")
        time.sleep(3)
        self.button.setText("")
        self.button.setEnabled(False)
        self.newButton.setText("New")


app = QtGui.QApplication(sys.argv)
a=Form()
a.show()
app.exec_()

请解释或演示如何使新按钮出现在方法中。

4

1 回答 1

0

你永远不会在addButton. 根本不需要调用repaintor update。一旦控件返回事件循环,您就会在屏幕上看到新按钮。

作为概念验证,您的代码可以修改为 callQCoreApplication.processEvents()而不是repaint(). 不过,它仍然是糟糕的代码。你不应该打电话sleep- 当你这样做时,你的代码实际上什么都没有发生,所以它完全没有意义。

基本上,只需添加按钮并退出该方法。它会起作用的。你无缘无故地把事情复杂化了。

于 2014-04-28T15:09:22.157 回答