多次调用 `QObject.thread()` 在 pyqt5 中返回不同的结果

问题描述 投票:0回答:0

我创建了一个小部件,其中包含两个方法。当我在这两个方法中调用

self.thread()
时,
self.thread()
返回的结果是不同的。为什么?

这是我的代码:

from PyQt5.QtWidgets import QWidget, QApplication
import sys
from PyQt5.QtCore import QThread


class MainWindow(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.resize(100, 100)
        self.test()
        self.test2()
        # self.test()

    def test(self):
        self.test_threader = QThread()
        print('\n')
        print("a new thread in test func", self.test_threader)
        print(f"MainWindow thread in test func {self.thread()}")
        print('\n')
        self.test_threader.deleteLater()

    def test2(self):
        self.test2_threader = QThread()
        print("a new thread in test2 func", self.test2_threader)
        print(f"MainWindow thread in test2 func {self.thread()}")
        self.test2_threader.deleteLater()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    print("\n")
    print(f"Application thread: {QApplication.instance().thread()}")
    print(f"MainWindow thread: {win.thread()}")
    sys.exit(app.exec())

控制台输出结果为:

a new thread in test func <PyQt5.QtCore.QThread object at 0x0000016CB1A77A60>
MainWindow thread in test func <PyQt5.QtCore.QThread object at 0x0000016CB1A77AF0>


a new thread in test2 func <PyQt5.QtCore.QThread object at 0x0000016CB1A77AF0>
MainWindow thread in test2 func <PyQt5.QtCore.QThread object at 0x0000016CB1A77B80>


Application thread: <PyQt5.QtCore.QThread object at 0x0000016CB1A77B80>
MainWindow thread: <PyQt5.QtCore.QThread object at 0x0000016CB1A77B80>

我想知道为什么会出现这种差异。谢谢!

python multithreading qt pyqt5 qthread
© www.soinside.com 2019 - 2024. All rights reserved.