gpt4 book ai didi

python - 如何将函数连接到主线程之外的 PyQt 信号

转载 作者:行者123 更新时间:2023-12-01 01:22:00 25 4
gpt4 key购买 nike

我正在创建一个 PyQt 应用程序,我希望有一个后台线程来连接一些事件处理程序,然后永远循环直到主窗口关闭。我遇到的问题是,我连接的事件处理程序只有在我的 MainWindow 类中定义的函数时才起作用。我在下面创建了一个最小的重现:

import threading
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QVBoxLayout


class MainWindow(QDialog):
def __init__(self):
super(MainWindow, self).__init__()

self.button1 = QPushButton("Click Me", self)
self.button2 = QPushButton("Me Too!", self)

layout = QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
self.setLayout(layout)

def test(self):
print("test inside class")


def test2():
print("test outside class")


def main(window):
window.button1.clicked.connect(window.test)
window.button2.clicked.connect(test2)
# Loop that runs in thread...


app = QApplication([])
window = MainWindow()
window.show()
threading.Thread(target=main, args=[window]).start()
app.exec_()

当我运行此代码时,第一个按钮按预期将消息打印到控制台,但第二个按钮在单击时不执行任何操作。如果我在主线程中运行 main(window) 函数,则两个按钮都可以工作。我知道在我的小示例程序中,这将是显而易见的解决方案,但由于解释起来很复杂,我需要能够从应用程序中的后台线程连接事件处理程序。为什么当我在主线程之外连接像 test2() 这样在 MainWindow 类之外定义的函数时,它不起作用?

最佳答案

我仍在找出问题的原因,但解决方案是指示连接类型,在本例中为 Qt::DirectConnection ,这将使函数 test2 在同一线程上运行发出信号的对象(发出信号的对象是位于主线程中的按钮)。

import threading
from PyQt5 import QtCore, QtWidgets

class MainWindow(QtWidgets.QDialog):
def __init__(self):
super(MainWindow, self).__init__()
self.button1 = QtWidgets.QPushButton("Click Me")
self.button2 = QtWidgets.QPushButton("Me Too!")
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button1)
layout.addWidget(self.button2)

@QtCore.pyqtSlot()
def test(self):
print("test inside class")

def test2():
print("test outside class")

def main(window):
window.button1.clicked.connect(window.test)
window.button2.clicked.connect(test2, QtCore.Qt.DirectConnection)
while True:
QtCore.QThread.sleep(1)

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
threading.Thread(target=main, args=(window,), daemon=True).start()
sys.exit(app.exec_())

关于python - 如何将函数连接到主线程之外的 PyQt 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53730451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com