【发布时间】:2014-06-12 05:56:54
【问题描述】:
我不明白是什么机制/触发器导致布局更新。在我创建的简单示例中,按钮的文本在方法内实时更新,但布局直到方法完成后才会更新,即使正确报告了“我应该看到 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_()
请解释或演示如何使新按钮出现在方法中。
【问题讨论】:
-
你需要在
layout.update()之后调用repaint(),而不是之前。 -
@PavelStrakhov 不,这段代码从根本上被破坏了,如果没有很好的理由,永远不应该调用
repaint。repaint(文本在整个 qtbase 模块中只出现了 95 次,而update(出现了 1132 次!这应该很重要。
标签: python qt refresh pyside qlayout