pyside 小部件与 threading.Thread 类一起运行 [英] pyside widget run with threading.Thread class
问题描述
我从 QtDesigner 获得了一个小部件,并通过 pyside 将 .ui 文件转换为 .py 文件.现在我希望该小部件组织一个数据库和一个单独的 threading.Thread(在同一模块中)来打开和读取数据库并发送到 UDP.事实上,我知道如何分开处理所有这些问题,但将其放在一起很难.我应该在我的小部件类中使用线程作为一个类吗:
I have obtained a widget from a QtDesigner and converted .ui file to .py file by pyside. now I want that widget to organize a database and an apart threading.Thread (in same module) to open and read database and send to UDP. the fact that I know how to deal with all these apartly but when bringing together it is hard. should I use thread as a class inside my widget class which is:
def setupUi(self, Form):
...
def retranslateUi(self, Form):
...
if __name__ == "__main__":
...
Form.show()
还有谁能举一个使用该小部件运行另一个线程的示例?
and also can anyone give an example for running another thread with that widget?
提前致谢
推荐答案
我举个例子,在 PySide/PyQt 中使用 QThreads 实现多线程和与其他 Widget 的通信.我自己用.
I give you an example for using QThreads in PySide/PyQt to achieve multithreading and communication with other Widgets. I use it myself.
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()
这篇关于pyside 小部件与 threading.Thread 类一起运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!