QT practical tutorial:
Article directory
Source address: QT calls external programs
call system command
Obviously, the operating system provides more complete instructions for functions such as copying and moving. QT
Classes are provided QProcess
for invoking system instructions, just like in the C language system
.
For example, Windows
the copy command is also available in copy
, then drag a button, rename it btnCopyFile
, then go to the slot, add the click
action
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, cpPro
is a QProcess, used in the final call cpPro.start(code,para)
, which code
is the instruction to be executed, the format is QString
; para
is the instruction list, the type is QStringList
, that is QList<QString>
.
The effect is
system command return value
QProcess
The 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 ls
command as an example (of course, Windows itself does not have ls, you can use dir)
Its effect is
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:
waitForStarted()
: block until the external program startswaitForReadyRead()
: Block until new data in the output channel is readablewaitForBytesWritten()
: Block until data in the input channel is writtenwaitForFinished()
: block until the external program ends