[QT] Use QProcess to call an external program

QT practical tutorial:


Source address: QT calls external programs

call system command

Obviously, the operating system provides more complete instructions for functions such as copying and moving. QTClasses are provided QProcessfor invoking system instructions, just like in the C language system.

For example, Windowsthe copy command is also available in copy, then drag a button, rename it btnCopyFile, then go to the slot, add the clickaction

void MainWindow::on_btnCopyFile_clicked()
{
    
    
    QString oldName = QFileDialog::getOpenFileName(this,"请选择文件");
    QString newName = QFileDialog::getSaveFileName(this,"请输入文件名");
    QProcess cpPro(this);
    QString code = "copy";
    ui->txtContent->setText(code);
    QStringList para;
    para << oldName << newName;
    foreach(QString item, para)
        ui->txtContent->append(item);
    cpPro.start(code, para);
}

Among them, cpProis a QProcess, used in the final call cpPro.start(code,para), which codeis the instruction to be executed, the format is QString; parais the instruction list, the type is QStringList, that is QList<QString>.

The effect is

insert image description here

system command return value

QProcessThe power of the command line is that it can not only execute the command line command of the system, but also capture the return value of the command line. Take the lscommand as an example (of course, Windows itself does not have ls, you can use dir)

Its effect is

insert image description here

code is

void MainWindow::on_btnListFiles_clicked()
{
    
    
    QString folder = QFileDialog::getExistingDirectory(this,"请选择文件夹");
    ui->lineTitle->setText(folder);
    QProcess cmd;
    cmd.start("dir",QStringList()<<folder);
    cmd.waitForStarted();
    cmd.waitForFinished();
    ui->txtContent->append(cmd.readAllStandardOutput());
}

Compared with the previous code, two are added wait, one is added read. As the name suggests, the former is used to wait for the command to be opened and completed, and the latter is used to obtain the standard output of the command line.

This involves the life cycle of QProcess:

  1. waitForStarted(): block until the external program starts
  2. waitForReadyRead(): Block until new data in the output channel is readable
  3. waitForBytesWritten(): Block until data in the input channel is written
  4. waitForFinished(): block until the external program ends

Guess you like

Origin blog.csdn.net/m0_37816922/article/details/124359078