栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Qt模拟Linux终端 1 - Linux指令调用

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Qt模拟Linux终端 1 - Linux指令调用

 

在一些特定场合中,直接调用Linux系统中自带的终端来执行Linux命令是不太适用的,有时用户就希望能不打开终端,直接在软件界面中输入命令。对于这种情况,可以使用QProcess来实现。

Qt对于QProcess的描述如下:

The QProcess class is used to start external programs and to communicate with them.

To start a process, pass the name and command line arguments of the program you want to run as arguments to start(). Arguments are supplied as individual strings in a QStringList.

QProcess 类用于启动外部程序并与它们通信。

要启动进程,请将要运行的程序的名称和命令行参数作为参数传递给 start()。 参数作为 QStringList 中的单个字符串提供。

代码实现
  • 一个QLineEdit用于输入命令,回车时响应操作;
  • 一个QtextBrowser用于输出信息;

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 

class QProcess;

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_lineEdit_returnPressed();
    void readBashStandardOutputInfo();
    void readBashStandardErrorInfo();

private:
    Ui::MainWindow *ui;
    QPointer m_process;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_process = new QProcess;
    m_process->start("bash");
    m_process->waitForStarted();

    connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readBashStandardOutputInfo()));
    connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readBashStandardErrorInfo()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_lineEdit_returnPressed()
{
    QString _str = ui->lineEdit->text();
    ui->textBrowser->append("Linux:~$ " + _str);
    m_process->write(ui->lineEdit->text().toLocal8Bit() + 'n');
    ui->lineEdit->clear();
}

void MainWindow::readBashStandardOutputInfo()
{
    QByteArray _out = m_process->readAllStandardOutput();
    if(!_out.isEmpty())   ui->textBrowser->append(QString::fromLocal8Bit(_out));
}

void MainWindow::readBashStandardErrorInfo()
{
    QByteArray _out = m_process->readAllStandardError();
    if(!_out.isEmpty())   ui->textBrowser->append(QString::fromLocal8Bit(_out));
}

 

拓展

到现在为止,已经可以做到在自己的Qt软件中调用Linux指令了,由此可以拓展一下:自定义一些系统里不存在的“指令”,输入这个“指令”就调用对应的系统指令或者完成一系列的系统操作,类似Linux中的alias,但可以做的更多。比如可以让不会用Linux,不了解Linux任何一个指令的外行使用者通过该软件达到自己想要的操作(当然这个操作得开发者提前定义好)。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/338784.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号