QT practical tutorial:
- QT preliminary timer
- QT signals and slots
- QT multi-threading combat
- QT file read and write
- QT calls external programs
Source address: [QT] Implementing a command line through QProcess
After understanding QProcess
the power, you can implement a system command line.
Create a new QT project, then drag one lineEdit
to rename lineCode
; drag one textBrowser
to rename txtRecv
. Right click lineEdit
to go to the slot and add an returnPressed()
action to it.
Its code is
void MainWindow::on_lineCode_returnPressed()
{
QProcess cmd;
QString codes = ui->lineCode->text();
QStringList para = codes.split(" ");
cmd.start(para.first(),para.sliced(1));
cmd.waitForStarted();
cmd.waitForFinished();
ui->lineCode->setText("");
ui->txtRecv->append(codes);
ui->txtRecv->append(cmd.readAllStandardOutput());
}
The effect is
There is a problem with this, that is, the error cannot be displayed. Obviously, the last input is qnmd
not a command, but there is no prompt, so it needs to print the error. So pull a new one txtcontent
, then change the code to
void MainWindow::on_lineCode_returnPressed()
{
QProcess cmd;
QString codes = ui->lineCode->text();
QStringList para = codes.split(" ");
cmd.start(para.first(),para.sliced(1));
cmd.waitForStarted();
cmd.waitForFinished();
ui->lineCode->setText("");
QString output = cmd.readAllStandardOutput();
if(!output.isEmpty()){
ui->txtRecv->append(codes);
ui->txtRecv->append(output);
}
QString err = cmd.readAllStandardError();
if(!err.isEmpty()){
ui->txtError->append(codes);
ui->txtError->append(err);
}
}
The effect is
But this does not actually solve the problem of wrong instructions. Since qnmd
it is not a valid instruction, there is neither standard output nor standard error.
In order to identify this situation, a member function can be called error()
, and its return value is an enumeration type. When the return value 0
is, it means that the startup program failed.
The effect is
just waitForFinished();
insert below
if(cmd.error()==0)
ui->txtError->append(codes+" error!!!\n请输入正确的指令");
The error()
returned enumeration type is as follows
QProcess:: |
value | describe |
---|---|---|
FailedToStart | 0 | process failed to start |
Crashed | 1 | Crash after process succeeds |
Timedout | 2 | The last call to waitFor...() function timed out. At this point, the state of QProcess remains unchanged, and functions of type waitFor...() can be called again |
WriteError | 3 | There was an error writing data to the process. If the process has not started, or the input channel is closed. |
ReadError | 4 | Error reading data from process. If the process has not started |
UnknownError | 5 | Default return value, unknown or no error. |
In the end, I still feel that something is wrong. The main reason is that the current position will be given in the command line. This is not difficult, just use
QString path = QCoreApplication::applicationDirPath();
codes = path + ">" + codes;
Then you can see