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())
当我在文本框中键入“ close ”时,它可以很好地工作,但是当我键入“ removeFocus ”时,它仍然可以工作,但出现此错误:
QObject::killTimer: Timers cannot be stopped from another thread
即使程序正在运行,为什么也会出现这样的错误?
(由于我想做的过程非常简单,所以我认为我不能做很多细节。我刚刚开始学习Python。这是我第一次使用此网站。很抱歉,创建帖子时出错(谢谢)
在Qt中,您不能从其他线程访问或修改GUI信息(有关更多信息,请参阅此信息),因为它不能保证它可以正常工作(GUI元素不是线程安全的),幸运的是,您没有问题,但是它实际使用您的方法很危险。
在您的情况下,也不必使用线程,因为使用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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句