Let's look at a more complex example, invoking a system command, where I'm using Windows, so I need to call dir; if you're compiling on Linux, you need to change to LS.
Mainwindow.h
- #ifndef Mainwindow_h
- #define Mainwindow_h
- #include <QtGui>
- Class MainWindow: Public Qmainwindow
- {
- Q_object
- Public
- MainWindow (Qwidget *parent = 0);
- ~mainwindow ();
- Private Slots:
- void OpenProcess ();
- void Readresult (int exitCode);
- Private
- Qprocess *p;
- };
- #endif//Mainwindow_h
Mainwindow.cpp
- #include "Mainwindow.h"
- Mainwindow::mainwindow (Qwidget *parent)
- : Qmainwindow (parent)
- {
- p = New qprocess (this);
- Qpushbutton *BT = new Qpushbutton ("Execute Notepad", this );
- Connect (BT, SIGNAL (clicked ()), this , SLOT (OpenProcess ()));
- }
- Mainwindow::~mainwindow ()
- {
- }
- void Mainwindow::openprocess ()
- {
- P->start ("cmd.exe", Qstringlist () << "/C" << "dir");
- Connect (p, SIGNAL (finished (int)), this , SLOT (readresult (int)));
- }
- void Mainwindow::readresult (int exitCode)
- {
- if (ExitCode = = 0) {
- qtextcodec* Gbkcodec = Qtextcodec::codecforname ("GBK");
- QString result = Gbkcodec->tounicode (P->readall ());
- Qmessagebox::information (This, "dir", result);
- }
- }
We have added only one slot function. In the slot where the button is clicked, we run the instruction through the Qprocess::start () function
cmd.exe/c dir
Here is to say, open the system cmd program and then run the dir command. If you have any questions about the parameter/C, you have to consult the relevant manual for Windows. Oh, that's not a Qt problem anymore. Then our process's finished () signal is connected to the newly added slot. This signal has a parameter int. As we know, the main () function always returns an int, the exit code, for A/C + + program to indicate whether the program exits normally. The int parameter here is the exit code. In the slot, we check if the exit code is 0, generally, if the exit code is 0, the description is normal exit. The results are then displayed in the Qmessagebox. How do we do that? Originally, the qprocess::readall () function can read out the program output. We use this function to get all the output, and since it returns the Qbytearray type, it is then converted to QString display. Also note that in the text Windows uses GBK encoding, and Qt uses Unicode encoding, so need to do a conversion, otherwise there will be garbled, you can try.
Well, interprocess interaction says so, by looking at the document you can find out how to use qprocess to implement process monitoring, or a function that allows the QT program to wait for the process to finish before continuing.
This article is from the "Bean Space" blog, make sure to keep this source http://devbean.blog.51cto.com/448512/305116
Call a system command and read its output value (using Qprocess.readall)