python-3.x PyQt5无法重绘微件

rhfm7lfc  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(208)

强制重绘不会重绘PyQt5小部件(Qlabel、QTextEdit,甚至QProgressBar等)
测试平台:Linux、Mac操作系统
PyQt5版本:5.15.7
从管道安装
例如,我创建了一个简单的应用程序,在for循环中更新QLabel小部件中的文本。

import sys
from time import sleep
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.text = QLabel('Test', self)
        self.text.move(10, 10)
        self.text.resize(60,20)

        self.button =  QPushButton('Run', self)
        self.button.move(17,40)
        self.button.clicked.connect(self.some_activity)

        self.setGeometry(300, 300, 100, 80)
        self.show()

    def some_activity(self):
        for i in range(100):
            text = f'i = {i}'
            self.text.setText(text)
            # self.text.update() -> Nothing happens (it shouldnt: https://doc.qt.io/qt-5/qwidget.html#update)
            self.text.repaint() # -> Nothing happens
            self.repaint() # -> Nothing happens
            print(f'Text updated: {text}')
            sleep(0.03)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

视频演示:link

lhcgjxsq

lhcgjxsq1#

只需要使用QThread在我的程序中使用for循环
感谢@musicamante的帮助。

import sys
from time import sleep
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)

class Thread(QtCore.QThread):
    signal = QtCore.pyqtSignal(str)
    def __init__(self, parent=None): QtCore.QThread.__init__(self, parent)

    def run(self): 
        for i in range(100):
            text = f'i = {i}'
            print(f'Text updated: {text}')
            self.signal.emit(text)
            sleep(.3)

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.text = QLabel('Test', self)
        self.text.move(10, 10)
        self.text.resize(60,20)

        self.thread = Thread()
        self.thread.signal.connect(self.signal, QtCore.Qt.QueuedConnection)

        self.button =  QPushButton('Run', self)
        self.button.move(17,40)
        self.button.clicked.connect(self.thread.start)

        self.setGeometry(300, 300, 100, 80)
        self.show()
    
    def signal(self, text): self.text.setText(text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

相关问题