python - 向 Python QProcess 示例添加按钮和单独的窗口

标签 python pyqt qprocess

我正在尝试使用 QProcess 并将标准输出读取到由按钮启动的 QTextEdit。我该如何适应 this example这样做?我是否必须为 QProcess 调用一个单独的类?

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


class MyQProcess(QProcess):     
  def __init__(self):    
   #Call base class method 
   QProcess.__init__(self)
   #Create an instance variable here (of type QTextEdit)
   self.edit    = QTextEdit()
   self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
   self.edit.show()   

  #Define Slot Here 
  @pyqtSlot()
  def readStdOutput(self):
    self.edit.append(QString(self.readAllStandardOutput()))


def main():  
    app     = QApplication(sys.argv)
    qProcess    = MyQProcess()

    qProcess.setProcessChannelMode(QProcess.MergedChannels);    
    qProcess.start("ldconfig -v")      
    QObject.connect(qProcess,SIGNAL("readyReadStandardOutput()"),qProcess,SLOT("readStdOutput()"));

    return app.exec_()

if __name__ == '__main__':
    main()

最佳答案

使用QPushButton制作一个按钮。

使用QPushButton.clicked.connect绑定(bind)事件。

例如:

import sys

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


class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.edit = QTextEdit()
        self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
        self.button = QPushButton('Run ldconfig')
        self.button.clicked.connect(self.onClick)
        layout = QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

    @pyqtSlot()
    def readStdOutput(self):
        self.edit.append(QString(self.proc.readAllStandardOutput()))

    def onClick(self):
        self.proc = QProcess()
        self.proc.start("echo hello")
        self.proc.setProcessChannelMode(QProcess.MergedChannels);
        QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"));

def main():
    app = QApplication(sys.argv)
    win = MyWindow()
    win.show()
    return app.exec_()

if __name__ == '__main__':
    main()

关于python - 向 Python QProcess 示例添加按钮和单独的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459770/

相关文章:

python - 如何获取 tkinter 菜单栏标签值?

python - PyQT线程的最简单方法

python - 如何在 PyQt 环境中将两个滚动条(垂直和水平)设置为同一个小部件?

python - pyqt中的切换按钮

python - 如何在 PySide 中获取 QProcess 运行的命令的输出?

c++ - 启动/运行外部可执行文件并查看其输出日志

python - 如何解码 HTTP 中 Content-Disposition header 的文件名参数?

python - 没有名为 _sqlite3 的模块

python - 具有 Python 代码完成功能的 Emacs > 代码完成建议未弹出

python - 使用 PySerial 从串口读取二进制数据