Home
Categories
WIKI
Topic
User
LANGUAGE:
中文
English
新手学linux分享个刚写的终端模拟器
社区开发
919
views ·
3
replies ·
To
floor
Go
nohacks
deepin
2020-04-20 04:09
Author
本帖最后由 nohacks 于 2020-4-25 09:59 编辑
部分代码如下:
#include "terminal.h"
#include "ui_terminal.h"
#include
#include
#include
#include
#define T_PrivPtr( o ) (( StationaryLampSet *) o )
Terminal::Terminal(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Terminal)
{
ui->setupUi(this);
//注册监视对象
ui->textEdit->installEventFilter(this);
//初始化QProcess
cmd=new QProcess(this);
connect(cmd , SIGNAL(readyReadStandardOutput()) , this , SLOT(on_readoutput()));
connect(cmd , SIGNAL(readyReadStandardError()) , this , SLOT(on_readerror()));
//注册启动事件
QTimer::singleShot(0, this, SLOT(init()));
}
Terminal::~Terminal()
{
//销毁外部程序
if(cmd)
{
cmd->close();
cmd->waitForFinished();
}
delete ui;
}
void Terminal::init()
{
cmd->start("bash"); //启动终端(Windows下改为cmd)
cmd->waitForStarted(); //等待启动完成
ui->textEdit->append("user@Terminal# ");
}
void Terminal::write(){
int pos=0;
QString word= ui->textEdit->toPlainText();
QRegExp rxlen("user@Terminal#(.+)(\\n|$)");
rxlen.setMinimal (true) ;
pos=rxlen.lastIndexIn(word);
if(pos!=-1){
QString ch = rxlen.cap(1).trimmed()+"\n";
char* shell; QByteArray ba = ch.toLatin1(); shell=ba.data();
cmd->write(shell);
//Terminal::checkshell();
}
}
void Terminal::checkshell(){
QString word= ui->textEdit->toPlainText().trimmed();
QString w=word.mid(word.length()-1,word.length());
if(w!="#"){
ui->textEdit->append("user@Terminal# ");
}
}
//监视对象
bool Terminal::eventFilter(QObject *target, QEvent *event)
{
/*处理按键消息 */
if (target == ui->textEdit && event->type() == QEvent::KeyPress){
/*强制类型转换 */
QKeyEvent *keyEvent = static_cast(event);
if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == 16777220) {
Terminal::write();
return true;
}
}
/*处理按键消息 */
return QWidget::eventFilter(target, event);
}
void Terminal::on_readoutput()
{
ui->textEdit->append(cmd->readAllStandardOutput().data()); //将输出信息读取到编辑框
Terminal::checkshell();
}
void Terminal::on_readerror()
{
ui->textEdit->append(cmd->readAllStandardError().data());
Terminal::checkshell();
}
Copy the Code
请多多指教,看有没有更好的实现方式,目前用的
QProcess
组件
发送权限命令,请添加-S 选项
例如:sudo -S fdisk -l
项目地址:https://github.com/xymov/deepin-Terminal
Reply
Like 0
Favorite
View the author
All Replies
走钢丝
deepin
2020-05-11 19:16
#1
支持一下。。
Reply
Like 0
View the author
lookfor
deepin
2020-05-11 19:39
#2
软件名字应该修改一下
Reply
Like 0
View the author
ucSec
deepin
2020-05-15 22:22
#3
放码云上?
Reply
Like 0
View the author
Please
sign
in first
Featured Collection
Change
[Tutorial] deepin25 WSL Offline Installation Guide
UOS AI 2.8 Released! Three New Intelligent Agents & Major Evolution
Solid Q&A | deepin 25 Common Questions – The Immutable System Edition
New Thread
Popular Ranking
Change
WiFi Drivers
Popular Events
More
部分代码如下:
发送权限命令,请添加-S 选项
例如:sudo -S fdisk -l
项目地址:https://github.com/xymov/deepin-Terminal