为什么不同方法的不同行为

时间:2021-03-08 07:41:21

标签: python python-3.x multithreading pyqt pyqt5

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()

我想更改窗口的标题。为此,我使用了 3 种方法:

  • 方法一:直接调用函数
  • 方法二:直接在不同线程中调用函数
  • 方法 3: 在包装函数中调用该函数,然后在不同的线程中调用该包装函数。

注意:我不知道我为什么使用 method 3,但令人震惊的是为什么 method 2method 3 的运行方式不同。 为什么?

Method 2 冻结了应用程序,而 Method 3 运行正常。 我认为两者都会给出相同的结果,但他们没有。如果有人会给出适当的解释,那将是一个很大的帮助。

1 个答案:

答案 0 :(得分:2)

Qt 建议不要从辅助线程修改 GUI,这不是因为它无法执行,而是它不能保证在所有情况下都能正确运行。

OP 指出的是它的一个示例,因为例如代码可以在 Linux 中使用 KDE 作为桌面管理器,但不能在 Windows 中运行。

建议:不要直接从另一个线程创建或修改 GUI 元素。