【问题】
源码:
class Windows(QtGui.QWidget): # Creates a widget containing: # - a QLineEdit (status_widget) # - a button, connected to on_run_clicked def on_run_clicked(self): def update(text): self.widget.setText(text) threading.Thread(target=run, args=(update, )).start()
但是如果将 QLineEdit换成QTextEdit,并使用了append方法就会得到以下错误:
QObject::connect: Cannot queue arguments of type ‘QTextCursor‘
(Make sure ‘QTextCursor‘ is registered using qRegisterMetaType().)
【解决】
我们不能通过线程来修改UI,较为安全的修改用户界面的方式是向UI窗口发送信号(signal),较为简单的方式是使用 Qt threading
class MyThread(QtCore.QThread): updated = QtCore.pyqtSignal(str) def run( self ): # do some functionality for i in range(10000): self.updated.emit(str(i)) class Windows(QtGui.QWidget): def __init__( self, parent = None ): super(Windows, self).__init__(parent) self._thread = MyThread(self) self._thread.updated.connect(self.updateText) # create a line edit and a button self._button.clicked.connect(self._thread.start) def updateText( self, text ): self.widget.setText(text)
时间: 2024-10-18 16:58:09