除非主窗口未聚焦,否则 QLabel 不会更新

I-w*_*-Ki 3 python pyqt pyqt5

我正在尝试使用 PyQt5 与 Python 3.7.3 和 macOS 10.14.6 来“Hello World”。执行pyqt_helloworld.py下面并单击按钮会将标签更新为“Hello World”。

但是,当单击按钮时,文本不会更改,直到我手动关注其他应用程序的窗口时,标签才会更新。如何在不取消 PyQt 应用程序焦点的情况下更新 QLabel?

提前致谢!

pyqt_helloworld_ui.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_HelloWorld(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(70, 40, 201, 21))
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(130, 90, 113, 32))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "foobar"))
        self.pushButton.setText(_translate("Dialog", "Click"))
Run Code Online (Sandbox Code Playgroud)

pyqt_helloworld.py

import sys

from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow

from pyqt_helloworld_ui import Ui_HelloWorld


class HelloWorldGui(QMainWindow, Ui_HelloWorld):
    def __init__(self, parent=None):
        super(HelloWorldGui, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.setTextHelloWorld)

    def setTextHelloWorld(self):
        self.label.setText("Hello World")


if __name__ == '__main__':
    argvs = sys.argv
    app = QApplication(argvs)
    hello_world_gui = HelloWorldGui()
    hello_world_gui.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

小智 5

该问题自 5.11.0 起出现在 PyQt5 中(测试了 5.11.x、5.12.x 和 5.13),以及 MacOS 上的 PySide2 v.5.13(测试了 10.14 和 10.12.6)。v.5.10.1 工作正常。Linux 和 Windows 下不存在该问题添加对重绘方法的调用可修复该问题。

def setTextHelloWorld(self):
    self.label.setText("Hello World")
    self.label.repaint()
Run Code Online (Sandbox Code Playgroud)