我从QtDesigner获取了一个小部件,并通过pyside将.ui文件转换为.py文件。现在我希望该小部件组织一个数据库和一个独立的threading.Thread(在同一个模块中)来打开和读取数据库并发送到UDP。事实上,我知道如何分开处理所有这些,但是当汇集它时很难。我应该在我的widget类中使用thread作为类:
def setupUi(self, Form):
...
def retranslateUi(self, Form):
...
if __name__ == "__main__":
...
Form.show()
并且还有人可以举例说明使用该小部件运行另一个线程吗?
提前致谢
答案 0 :(得分:1)
我举一个例子,在PySide / PyQt中使用QThreads来实现多线程和与其他Widgets的通信。我自己用它。
from PySide import QtCore
class Master(QtCore.QObject):
command = QtCore.Signal(str)
def __init__(self):
super().__init__()
class Worker(QtCore.QObject):
def __init__(self):
super().__init__()
def do_something(self, text):
print('in thread {} message {}'.format(QtCore.QThread.currentThread(), text))
if __name__ == '__main__':
app = QtCore.QCoreApplication([])
# give us a thread and start it
thread = QtCore.QThread()
thread.start()
# create a worker and move it to our extra thread
worker = Worker()
worker.moveToThread(thread)
# create a master object and connect it to the worker
master = Master()
master.command.connect(worker.do_something)
# call a method of the worker directly (will be executed in the actual thread)
worker.do_something('in main thread')
# communicate via signals, will execute the method now in the extra thread
master.command.emit('in worker thread')
# start the application and kill it after 1 second
QtCore.QTimer.singleShot(1000, app.quit)
app.exec_()
# don't forget to terminate the extra thread
thread.quit()