如何制作一个可在PyQT中实时更新的可编辑小部件

时间:2013-12-31 09:40:46

标签: python linux qt pyqt pyqt4

我正在尝试创建一个在PyQT4中更新系统的GUI。我会这样做,以便它在GUI中的实时时间运行所有命令,以便您可以观看它更新。我不确定我会用什么类型的小部件来做这件事。

这样的例子就像wget在运行时如何具有下载的状态栏,将其输出放入小部件中。

我想你会使用子进程库来运行命令,然后以某种方式将输出定向到小部件的内容,但我完全不确定如何做到这一点。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我相信你可以使用一个简单的QLabel实例来执行此任务。但是,如果您需要更多花哨的可视化,您还可以使用只读QTextEdit等。

至于处理代码,如果碰巧选择QProcess而不是python中的子进程模块,你会写下面的代码。

来自PyQt4.QtCore的

导入QTimer,pyqtSignal,QProcess,pyqtSlot 来自PyQt4.QtGui导入QLabel

class SystemUpdate(QProcess)
    """
    A class used for handling the system update process
    """

    def __init__(self):
        _timer = QTimer()
        _myDisplayWidget = QLabel()

        self.buttonPressed.connect(self.handleReadyRead)
        self.error.connect(self.handleError)
        _timer.timeout.connect(self.handleTimeout)

        _timer.start(5000)

    @pyqtSlot()    
    def handleReadyRead(self):
        _readData = readAll()
        _myDisplayWidget.append(readData)

        if not _timer.isActive():
            _timer.start(5000)

    @pyqtSlot()
    def handleTimeout(self):
        if not _readData:
            _myDisplayWidget.append('No data was currently available for reading from the system update')
        else:
            _myDisplayWidget.append('Update successfully run')

    @pyqtSlot(QProcess.ProcessError)
    def handleError(self, processError)
        if processError == QProcess.ReadError:
            _myDisplayWidget.append('An I/O error occurred while reading the data, error: %s' % _process->errorString())

注意:我知道QLabel类没有附加方法,但您可以在可用方法的帮助下轻松编写这样的便捷包装。

至于完整性,这里是python子流程方法:

import subprocess
from PyQt4.QtGui import QLabel

output = ""
try:
    """
        Here you may need to pass the absolute path to the command
        if that is not available in your PATH, although it should!
    """
    output = subprocess.check_output(['command', 'arg1', 'arg2'], stderr=subprocess.STDOUT)
exception subprocess.CalledProcessError as e:
    output = e.output
finally:
    myDisplayWidget.append(output)