1、QProcess 打开一个bash终端,可以执行一般的命令,主要实现步骤如下
m_proces_bash = new QProcess;
m_proces_bash->start("bash");
m_proces_bash->waitForStarted();
connect(m_proces_bash,SIGNAL(readyReadStandardOutput()),this,SLOT(readBashStandardOutputInfo()));
connect(m_proces_bash,SIGNAL(readyReadStandardError()),this,SLOT(readBashStandardErrorInfo()));
2、向终端发送命令
void MainWindow::on_pushButton_bashrun_clicked()
{QString strCmd = ui->lineEdit_bashcmd->text();ui->textEdit_bashmsg->append("Linux:~$ "+strCmd);m_proces_bash->write(ui->lineEdit_bashcmd->text().toLocal8Bit() + '\n');ui->lineEdit_bashcmd->clear();
}
3、接收终端返回
void MainWindow::readBashStandardOutputInfo()
{QByteArray cmdout = m_proces_bash->readAllStandardOutput();if(!cmdout.isEmpty()){ui->textEdit_bashmsg->append(QString::fromLocal8Bit(cmdout));}QScrollBar* scroll = ui->textEdit_bashmsg->verticalScrollBar();scroll->setSliderPosition(scroll->maximum());
}
void MainWindow::readBashStandardErrorInfo()
{QByteArray cmdout = m_proces_bash->readAllStandardError();if(!cmdout.isEmpty()){ui->textEdit_bashmsg->append(QString::fromLocal8Bit(cmdout));}QScrollBar* scroll = ui->textEdit_bashmsg->verticalScrollBar();scroll->setSliderPosition(scroll->maximum());
}
4、当命令需要超级权限时,sudo xx 需要修改为sudo -S xx
例如:(1)ls 执行正常
(2)sudo ls 执行失败
(3)执行sudo -S ls 执行成功