2014-04-26 9 views
0

我不明白什麼機制/觸發器導致佈局更新。在我創建的簡單示例中,按鈕的文本在方法內實時更新,但佈局不會更新,直到方法完成後即使「我應該看到2個按鈕」被正確報告。我如何獲得佈局/窗口以將按鈕實時添加到佈局中?QLayout刷新機制不明白

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_() 

請解釋或演示如何使新按鈕出現在方法中。

+1

您需要在'layout.update()'之後調用'repaint()',而不是在它之前。 –

+0

@PavelStrakhov不,這段代碼基本上是壞的,不應該在沒有很好的理由的情況下調用'repaint'。文本'repaint('在整個qtbase模塊中只出現95次,'update'(1132次),這應該算作某種東西。 –

回答

0

您從不在addButton內運行事件循環。根本不需要撥打repaintupdate。只要控件返回到事件循環,您將在屏幕上看到新的按鈕。

作爲一個概念驗證,您的代碼可以修改爲撥打QCoreApplication.processEvents()而不是repaint()。不過,它仍然是不好的代碼。你不應該打電話給sleep - 雖然你這樣做了,但是在你的代碼中沒有任何事情發生,所以它完全沒有意義。

基本上,只需添加按鈕並退出該方法。它會工作。你根本沒有理由過分複雜。