我写了一个非常简约的程序,可以达到你的预期.以下是代码:
mainwindow.hpp
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
private slots:
void onReadyRead();
void onPushButtonClicked();
private:
QPushButton* pushButton;
QProcess *shell;
};
#endif // MAINWINDOW_HPP
main.cpp中
#include
#include
#include
#include "mainwindow.hpp"
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
{
pushButton = new QPushButton("Execute");
connect(pushButton, SIGNAL(clicked()),
this, SLOT(onPushButtonClicked()));
setCentralWidget(pushButton);
}
void MainWindow::onPushButtonClicked()
{
shell = new QProcess(this);
connect(shell, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
shell->start("python");
if (!shell->waitForStarted())
exit(1);
shell->write("print 'hello!'\n");
shell->closeWriteChannel();
if (!shell->waitForFinished())
exit(1);
qDebug() << "Shell error code:" << shell->error();
}
void MainWindow::onReadyRead()
{
QString text = shell->readAll();
qDebug() << text;
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MainWindow win;
win.show();
return app.exec();
}
实施说明:
>我通过添加QProces :: waitFor …()来使用同步API.
>我用QProcess :: closeWriteChannel()关闭了通信通道.
>我添加了一些调试输出,尤其是QProcess的错误代码非常有用.
这些事情共同展示了一个激励人心的问候!当按下按钮时.