gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:36 27 4
gpt4 key购买 nike

以下代码对网站执行 ping 操作并在 QTextEdit 中打印结果。一个按钮“运行”用于启动 ping。我想要另一个按钮“结束”,它可以在不关闭 GUI 的情况下在运行时停止 ping 过程。但目前,“结束”按钮会关闭整个 GUI 窗口。您对如何停止 ping 但保留 GUI 有什么想法吗,这样我就可以通过按“运行”按钮再次启动 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()

最佳答案

您必须将 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))

关于python - 如何在不关闭 GUI 窗口的情况下停止运行 PyQt5 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com