除非主窗口未聚焦,否则不会更新 QLabel [英] QLabel is not updated unless the mainWindow is unfocused

查看:41
本文介绍了除非主窗口未聚焦,否则不会更新 QLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyQt5 和 Python 3.7.3 和 macOS 10.14.6 来Hello World".执行下面的 pyqt_helloworld.py 并点击按钮将更新标签为Hello World".

I am trying "Hello World" using PyQt5 with Python 3.7.3 and macOS 10.14.6. Executing pyqt_helloworld.py below and clicking the button will update the label to "Hello World".

但是,当点击按钮时,文本并没有改变,直到我手动关注其他应用程序的窗口才更新标签.如何在不使 PyQt 应用程序失去焦点的情况下更新 QLabel?

However, when the button is clicked, the text is not changed, and it is not until I focus on the window of other application manually that the label is updated. How can I update QLabel without unfocusing the PyQt application?

提前致谢!

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

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

推荐答案

该问题存在于 PyQt5 自 5.11.0(已测试 5.11.x、5.12.x 和 5.13)和 MacOS 上的 PySide2 v.5.13(测试 10.14 和10.12.6).v.5.10.1 工作正常.Linux 和 Windows 下不存在此问题添加对 repaint 方法的调用可解决此问题.

the issue is present in PyQt5 since 5.11.0 (tested 5.11.x, 5.12.x and 5.13) and PySide2 v.5.13 on MacOS (tested 10.14 and 10.12.6). The v.5.10.1 works fine. The issue does not exist under Linux and Windows Adding a call to the repaint method fix the issue.

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

这篇关于除非主窗口未聚焦,否则不会更新 QLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆