简体   繁体   English

python qt pyside listbox逐行打印

[英]python qt pyside listbox print line by line

This piece of code (python3/Qt/PySide) is doing print line by line in ListBox (or something) when some job is done. 当完成某项工作时,这段代码(python3 / Qt / PySide)在ListBox中(一行)逐行打印。 Problem is lines are not refreshed when print is done. 问题是完成打印后,行没有刷新。 Some piece of wisdom, please. 请一些智慧。

import sys
from random import randint
from PySide import QtGui, QtCore
import time

def do_job ():
    time.sleep(randint(1, 8)/10.0)

def work():
    for i in range(14):
        do_job ()
        line = QtGui.QListWidgetItem("did job {}".format(i))
        print (line.text())
        w.lw.addItem(line)

app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
w.setGeometry(300, 300, 420, 240)
w.setWindowTitle('Some task')

w.btn1 = QtGui.QPushButton('do job', w)
w.btn1.move(300, 120)
w.btn1.clicked.connect(work)

w.btn2 = QtGui.QPushButton('die', w)
w.btn2.move(300, 180)
w.btn2.clicked.connect(QtCore.QCoreApplication.instance().quit)

w.lw = QtGui.QListWidget(w)
w.lw.move(20, 20)

w.show()
sys.exit(app.exec_())

The functions like sleep() block the GUI loop causing it to not be able to update the elements it manages, in addition to observing that in the load you can not interact with the GUI, such as changing its size. 诸如sleep()类的功能会阻止GUI循环,从而导致它无法更新其管理的元素,此外还要观察到在负载中您无法与GUI进行交互,例如更改其大小。 What you should do is look for some equivalent and in the case of Qt you can do a QEventLoop with a QTimer : 您应该做的就是寻找一些等效项,在Qt的情况下,您可以使用QTimer进行QEventLoop

def do_job():
    loop = QtCore.QEventLoop()
    QtCore.QTimer.singleShot(100*randint(1, 8), loop.quit)
    loop.exec_()

The following method is equivalent to time.sleep(delay) : 以下方法等效于time.sleep(delay)

def new_sleep(delay):
    loop = QtCore.QEventLoop()
    QtCore.QTimer.singleShot(int(delay*1000), loop.quit)
    loop.exec_()

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

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