问题
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?
Thanks in advance
回答1:
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()
来源:https://stackoverflow.com/questions/24165877/pyside-widget-run-with-threading-thread-class