简体   繁体   English

PyQt4 QMessageBox文本更改

[英]PyQt4 QMessageBox text change

I am using this simple code to show warning boxes: 我使用以下简单代码显示警告框:

w = QWidget() 
result = QMessageBox.warning(w, 'a', x, QMessageBox.Ok)

Is there any way to change MESSAGE dynamically? 有什么办法可以动态更改MESSAGE? I want to make a popup which will inform user abut progress of a task that is running in background. 我想制作一个弹出窗口,该弹出窗口将通知用户在后台运行的任务的进度。

Edit: 编辑:

Well I tried to do so making this script for testing: 好吧,我试图通过以下脚本进行测试:

def handleButton(self):
        self.msgBox = QMessageBox(self)
        self.msgBox.setWindowTitle("Title")
        self.msgBox.setIcon(QMessageBox.Warning)
        self.msgBox.setText("Start")
        self.msgBox.show()
        x = 0
        for x in range (100):
            x = x + 1
            print (x)
            self.msgBox.setText(str(x))
            self.msgBox.show()
            time.sleep(1)

The text only shows after finishing the 'for loop', why? 文本仅在完成“ for循环”后显示,为什么?

Instead of using a static method you could create an object of the class. 可以使用类的对象来代替静态方法。

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.msgBox = QMessageBox(self)
        self.msgBox.setWindowTitle("Title")
        self.msgBox.setIcon(QMessageBox.Warning)
        self.msgBox.setText("Start")
        self.msgBox.show()

        timer = QTimer(self)
        timer.timeout.connect(self.onTimeout)
        timer.start(1000)

    def onTimeout(self):
        self.msgBox.setText("datetime: {}".format(QDateTime.currentDateTime().toString()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Update: 更新:

The problem in your example is the use of time.sleep() . 您的示例中的问题是使用time.sleep() Qt is executed in an eventloop, this eventloop allows you to handle the events of the mouse, keyboard, redraw, etc. but the time.sleep() blocks the eventloop, this you can check trying to change the size of the window, you will see that you can not do it. Qt在一个事件循环中执行,该事件循环允许您处理鼠标,键盘,重绘等事件,但是time.sleep()阻止了该事件循环,您可以检查是否尝试更改窗口的大小,会看到你做不到。

Assuming you use time.sleep() to pause, then you must use QEventLoop with QTimer that does not block the Qt eventloop. 假设您使用time.sleep()进行暂停,则必须将QEventLoopQTimer配合使用,而QTimer不会阻塞Qt事件循环。

def handleButton(self):
    self.msgBox = QMessageBox(self)
    self.msgBox.setWindowTitle("Title")
    self.msgBox.setIcon(QMessageBox.Warning)
    self.msgBox.setText("Start")
    self.msgBox.show()

    for x in range(100):
        self.msgBox.setText(str(x+1))
        loop = QEventLoop()
        QTimer.singleShot(1000, loop.quit)
        loop.exec_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM