【问题标题】:pyside widget run with threading.Thread classpyside 小部件与 threading.Thread 类一起运行
【发布时间】:2014-06-11 14:42:40
【问题描述】:

我从 QtDesigner 获得了一个小部件,并通过 pyside 将 .ui 文件转换为 .py 文件。现在我希望该小部件组织一个数据库和一个单独的 threading.Thread(在同一模块中)以打开和读取数据库并发送到 UDP。事实上,我知道如何分开处理所有这些,但是当把它放在一起时就很难了。我应该在我的小部件类中使用线程作为一个类吗:

def setupUi(self, Form):
...
def retranslateUi(self, Form):
...
if __name__ == "__main__":
...
Form.show()

还有谁能举个例子来用那个小部件运行另一个线程?

提前致谢

【问题讨论】:

  • 这里有一些关于线程的documentation 和一个example
  • 我已经查过它们@Trilarion。谢谢你。除了您的建议链接(QObject)之外,还有其他方法可以使用我的小部件类将线程作为类运行吗?
  • 可以从QThread派生并实现run类。这很好,有一段时间甚至是推荐的方式。事件处理 afaik 会有问题,但如果你对结果感到满意,那就去做吧。否则使用 QObject 并移动到线程也没有那么多工作。
  • @Trilarion 您的示例是用 qt-script 编写的,我在 pyside(python3.3) 中运行我的代码。对不起,我无法让自己理解。
  • 语法几乎相同,但我还在下面发布了一个完整的示例。

标签: python pyside qt-designer python-multithreading


【解决方案1】:

我举一个例子,在 PySide/PyQt 中使用 QThreads 来实现多线程以及与其他 Widget 的通信。我自己用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-08
    • 2017-10-31
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2011-10-07
    • 2022-08-08
    • 2020-03-09
    相关资源
    最近更新 更多