如何在不关闭GUI窗口的情况下停止运行PyQt5程序?

时间:2017-09-25 21:12:40

标签: python pyqt pyqt5 qprocess

以下代码ping网站并在QTextEdit中打印结果。一键"运行"用于启动ping。我想要另一个按钮" End",它可以在运行时停止ping进程而不关闭GUI。但目前," End"按钮关闭整个GUI窗口。你有没有想过如何停止ping但保留GUI,所以我可以通过按" Run"再次启动ping。按钮。

import sys
from PyQt5 import QtCore,QtWidgets

class gui(QtWidgets.QMainWindow):
    def __init__(self):
        super(gui, self).__init__()
        self.initUI()

    def dataReady(self):
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(str(self.process.readAll()))
        self.output.ensureCursorVisible()

    def callProgram(self):
        # run the process
        # `start` takes the exec and a list of arguments
        self.process.start('ping',['127.0.0.1'])

    def initUI(self):
        # Layout are better for placing widgets
        layout = QtWidgets.QHBoxLayout()
        self.runButton = QtWidgets.QPushButton('Run')
        self.runButton.clicked.connect(self.callProgram)
        self.runButton1 = QtWidgets.QPushButton('End')
        self.runButton1.clicked.connect(self.close)

        self.output = QtWidgets.QTextEdit()

        layout.addWidget(self.output)
        layout.addWidget(self.runButton)
        layout.addWidget(self.runButton1)

        centralWidget = QtWidgets.QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

        # QProcess object for external app
        self.process = QtCore.QProcess(self)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyRead.connect(self.dataReady)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda: self.runButton.setEnabled(False))
        self.process.finished.connect(lambda: self.runButton.setEnabled(True))


#Function Main Start
def main():
    app = QtWidgets.QApplication(sys.argv)
    ui=gui()
    ui.show()
    sys.exit(app.exec_())
#Function Main END

if __name__ == '__main__':
    main() 

1 个答案:

答案 0 :(得分:1)

您必须将clicked信号与QProcess kill广告位相关联:

def initUI(self):
    [...]
    self.runButton1 = QtWidgets.QPushButton('End')
    # self.runButton1.clicked.connect(self.close)
    [...]

    # QProcess object for external app
    self.process = QtCore.QProcess(self)
    # QProcess emits `readyRead` when there is data to be read
    self.process.readyRead.connect(self.dataReady)
    self.runButton1.clicked.connect(self.process.kill)
    # Just to prevent accidentally running multiple times
    # Disable the button when process starts, and enable it when it finishes
    self.process.started.connect(lambda: self.runButton.setEnabled(False))
    self.process.finished.connect(lambda: self.runButton.setEnabled(True))