gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:38:59 24 4
gpt4 key购买 nike

我正在尝试使用 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"))

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

最佳答案

自 5.11.0(测试了 5.11.x、5.12.x 和 5.13)以来的 PyQt5 以及 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()

关于python - 除非主窗口未聚焦,否则 QLabel 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com