How do you invoke a Python program from Qt?
To call a Python program in Qt, you can use the QProcess class. Below is a simple example code:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import QProcess
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.button = QPushButton("调用Python程序", self)
self.button.setGeometry(100, 100, 200, 50)
self.button.clicked.connect(self.callPythonProgram)
def callPythonProgram(self):
pythonProcess = QProcess()
pythonProcess.start("python", ["path_to_your_python_script.py"])
pythonProcess.waitForFinished()
output = pythonProcess.readAllStandardOutput()
print(output.data().decode())
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
In the above code, we trigger the calling of a Python program by creating a QPushButton. In the callPythonProgram function, we create a QProcess object and use the start method to launch the Python program, where the first parameter is the path to the Python interpreter and the second parameter is the path to the Python script to be executed. We then use the waitForFinished method to wait for the completion of the Python program’s execution, and use the readAllStandardOutput method to read the standard output. Finally, we print the output to the console.
Make sure that the PyQt5 library is installed, and replace path_to_your_python_script.py with the actual path to your Python script. After running this Qt application, clicking the button will invoke the Python program and print the output to the console.