Home > Net >  How to run Python script from QT creator and print output to GUI
How to run Python script from QT creator and print output to GUI

Time:08-18

void MainWindow::on_pushButton_clicked()
{
QProcess p;

// get values from ini file
settings->setValue("EMail", ui->lineEditEMail->text());
settings->setValue("Password", ui->lineEditPassword->text());

settings->setValue("Chronological", ui->checkBox->isChecked());
settings->setValue("Current_info", ui->checkBox_2->isChecked());
settings->endGroup();

settings->sync();

// launch python code for login
QString  program( "C:/projects/build-test3-Desktop_Qt_6_4_0_MinGW_64_bit-Debug/venv/Scripts/python.exe");
QStringList  args = QStringList() << "index.py";
QProcess::execute( program, args );

}

I have this function that is executed after a button is clicked and I need to print the output of "index.py" in to my app. What widget should I use and how? From what I read QTextBrowser should do the trick but I'm not sure how to use it. GUI

This is how my GUI looks like. I'd like to use to output my results somewhere in button right. I didn't add the widget yet, because I'm not sure QTextBrowser is the one I need

CodePudding user response:

The widget you could use for this purpose is QTextEdit (you can set it to be read-only from the graphical user interface).

But if you want to get the output of the execution, you will need a proper instance of QProcess and call the QProcess::readAllStandardOutput() member function to get the standard output.

You may also be interested by QProcess::readAllStandardError() to get the errors in case of failure.


Edit (simple/basic example):

QProcess p;
p.start("path/to/python.exe", QStringList("script.py"));

p.waitForFinished();
QByteArray p_stdout = p.readAllStandardOutput();
QByteArray p_stderr = p.readAllStandardError();

// Do whatever you want with the results (check if they are not empty, print them, fill your QTextEdit contents, etc...)

Note: If you don't want to be blocking with QProcess::waitForFinished(), you can use a signal/slots connection on QProcess::finished() signal.

  • Related