I wanted to use the python interpreter in a QT C++ program, I tried to open a python console using QProcess:
QProcess shell; // this is declared in the class .h file
shell.start("python");
connect(&shell,SIGNAL(readyRead()),SLOT(shellOutput()));
shell.write("print 'hello!'\n");
But I didn't catch any outputs, where did I get it wrong, or is there a better way doing this?
I wrote a very minimalistic program that does what you expected. Below is the code:
mainwindow.hpp
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include <QtGui>
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 <QtCore>
#include <QtGui>
#include <QDebug>
#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();
}
Implementation notes:
QProces::waitFor...()
.QProcess::closeWriteChannel()
.QProcess
is quite helpful.These things together show a motivating hello!
when the pushbutton is pressed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With