为什么不同的方法会有不同的行为
Why the different behavior on different approach
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys, time, threading
class Main_(QMainWindow):
def __init__(self, *args, **kwargs):
super(Main_, self).__init__(*args, **kwargs)
self.resize(QSize(300, 250))
self.show()
def change_window_title(self, title):
self.setWindowTitle(title)
def fctn(title_fctn):
print('START')
time.sleep(5)
title_fctn('Test')
print('DONE')
app = QApplication(sys.argv)
window = Main_()
# Method 1
fctn(window.change_window_title)
# Method 2
threading.Thread(
target=lambda: window.change_window_title('test')
).start()
# Method 3
threading.Thread(
target=lambda: fctn(window.change_window_title)
).start()
app.exec()
我想更改 window 的标题。为此,我使用了 3 种方法:
- 方法一:直接调用函数
- 方法二:直接在不同线程中调用函数
- 方法 3: 在包装函数中调用函数,然后在不同的线程中调用该包装函数。
注:不知道为什么用了method 3
,但是很震惊为什么method 2
和method 3
运行 不同。 为什么?
Method 2
冻结了应用程序,而 Method 3
运行良好。 我以为两者会给出相同的结果,但他们没有。如果有人能给出适当的解释,那将是一个很大的帮助。
Qt 建议不要从辅助线程修改 GUI,这不是因为它不能执行,而是它不能保证在所有情况下都能正确运行。
OP 指出的是它的一个示例,因为例如代码在 Linux 中工作,KDE 作为桌面管理器,但在 Windows 中不工作。
建议:不要直接从另一个线程创建或修改 GUI 元素。
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys, time, threading
class Main_(QMainWindow):
def __init__(self, *args, **kwargs):
super(Main_, self).__init__(*args, **kwargs)
self.resize(QSize(300, 250))
self.show()
def change_window_title(self, title):
self.setWindowTitle(title)
def fctn(title_fctn):
print('START')
time.sleep(5)
title_fctn('Test')
print('DONE')
app = QApplication(sys.argv)
window = Main_()
# Method 1
fctn(window.change_window_title)
# Method 2
threading.Thread(
target=lambda: window.change_window_title('test')
).start()
# Method 3
threading.Thread(
target=lambda: fctn(window.change_window_title)
).start()
app.exec()
我想更改 window 的标题。为此,我使用了 3 种方法:
- 方法一:直接调用函数
- 方法二:直接在不同线程中调用函数
- 方法 3: 在包装函数中调用函数,然后在不同的线程中调用该包装函数。
注:不知道为什么用了method 3
,但是很震惊为什么method 2
和method 3
运行 不同。 为什么?
Method 2
冻结了应用程序,而 Method 3
运行良好。 我以为两者会给出相同的结果,但他们没有。如果有人能给出适当的解释,那将是一个很大的帮助。
Qt 建议不要从辅助线程修改 GUI,这不是因为它不能执行,而是它不能保证在所有情况下都能正确运行。
OP 指出的是它的一个示例,因为例如代码在 Linux 中工作,KDE 作为桌面管理器,但在 Windows 中不工作。
建议:不要直接从另一个线程创建或修改 GUI 元素。