【问题标题】:Timers cannot be stopped from another thread - Remove Focus无法从另一个线程停止计时器 - 删除焦点
【发布时间】:2020-03-31 23:57:05
【问题描述】:
import sys

from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit

class Worker(QThread):

    def __init__(self, textBox):
        super().__init__()
        self.textBox = textBox

    def run(self):
        while True:
            if self.textBox.text() == "close":
                app.quit()
                break

            if self.textBox.text() == "removeFocus":
                self.textBox.clearFocus()

class window(QWidget):
    def __init__(self):
        super().__init__()

        vBox = QVBoxLayout()
        self.setLayout(vBox)
        self.resize(600, 400)

        textBox = QLineEdit()
        vBox.addWidget(textBox)

        worker = Worker(textBox)
        worker.start()

        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = window()
    sys.exit(app.exec())

当我在 textBox 中输入“close”时,它工作得很好,但当我输入“removeFocus”时,它仍然有效,但我收到此错误:

QObject::killTimer: Timers cannot be stopped from another thread

为什么即使程序正在运行,我也会收到这样的错误?

(由于我想做的过程很简单,我觉得我不能说得太多。我刚开始学习Python。这是我第一次使用这个网站。我'对不起,如果我在创建帖子时犯了错误。谢谢)

【问题讨论】:

    标签: python multithreading pyqt pyqt5 qthread


    【解决方案1】:

    在 Qt 中,您不能从另一个线程访问或修改 GUI 信息(有关更多信息,请参阅 this),因为它不能保证它可以正常工作(GUI 元素不是 thread-safe),幸运的是,您没有问题,但实际使用你的方法很危险。

    在您的情况下,也不需要使用线程,因为使用来自 QLineEdit 的 textChanged 信号就足够了。

    import sys
    
    from PyQt5.QtCore import pyqtSlot
    from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit
    
    
    class Window(QWidget):
        def __init__(self):
            super().__init__()
    
            vBox = QVBoxLayout(self)
            self.resize(600, 400)
    
            self.textBox = QLineEdit()
            vBox.addWidget(self.textBox)
    
            self.textBox.textChanged.connect(self.on_text_changed)
    
        @pyqtSlot(str)
        def on_text_changed(self, text):
            if text == "close":
                QApplication.quit()
            elif text == "removeFocus":
                self.textBox.clearFocus()
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec())
    

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 2020-07-16
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多