code review!
代码
#include <QApplication>
#include <QPlainTextEdit>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QKeyEvent>
#include <QProcess>
#include <QScrollBar>
#include <QPushButton>
class TerminalWidget : public QWidget
{
// Q_OBJECT
public:
TerminalWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
// 创建终端输出控件
outputTextEdit = new QPlainTextEdit(this);
outputTextEdit->setReadOnly(true);
outputTextEdit->setStyleSheet("background-color: black; color: white;");
// 创建用户输入控件
inputLineEdit = new QLineEdit(this);
inputLineEdit->setStyleSheet("background-color: black; color: white; border: 1px solid white;");
// 创建清空按钮
clearButton = new QPushButton("Clear Terminal", this);
clearButton->setStyleSheet("color: white;"); // 设置按钮上的文本颜色为白色
connect(clearButton, &QPushButton::clicked, this, &TerminalWidget::clearTerminal);
// 连接输入控件的信号到槽函数
connect(inputLineEdit, &QLineEdit::returnPressed, this, &TerminalWidget::processCommand);
// 创建垂直布局并添加控件
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(outputTextEdit);
layout->addWidget(inputLineEdit);
layout->addWidget(clearButton);
// 设置布局
setLayout(layout);
// 设置窗口背景颜色
setStyleSheet("background-color: black;");
// 设置窗口标题
setWindowTitle("Terminal");
// 设置窗口大小
resize(800, 600);
// 设置焦点到输入框
inputLineEdit->setFocus();
}
protected:
void keyPressEvent(QKeyEvent *event) override
{
if (event->key() == Qt::Key_Up)
{
// 处理上箭头键,浏览历史命令
if (historyIndex > 0 && historyIndex <= commandHistory.size())
{
historyIndex--;
inputLineEdit->setText(commandHistory.at(historyIndex));
inputLineEdit->selectAll();
}
}
else if (event->key() == Qt::Key_Down)
{
// 处理下箭头键,浏览历史命令
if (historyIndex >= 0 && historyIndex < commandHistory.size() - 1)
{
historyIndex++;
inputLineEdit->setText(commandHistory.at(historyIndex));
inputLineEdit->selectAll();
}
else if (historyIndex == commandHistory.size() - 1)
{
historyIndex = commandHistory.size();
inputLineEdit->clear();
}
}
else
{
QWidget::keyPressEvent(event);
}
}
private slots:
void processCommand()
{
// 获取用户输入的命令
QString command = inputLineEdit->text();
// 清空输入框
inputLineEdit->clear();
// 执行命令并将输出写入终端
QProcess process;
process.start(command);
process.waitForFinished();
QString output = process.readAll();
// 添加命令到历史记录
commandHistory.append(command);
historyIndex = commandHistory.size();
// 显示命令和输出
outputTextEdit->appendPlainText("$ " + command);
outputTextEdit->appendPlainText(output);
// 将滚动条滚动到底部,以显示最新的输出
outputTextEdit->verticalScrollBar()->setValue(outputTextEdit->verticalScrollBar()->maximum());
// 设置焦点到输入框
inputLineEdit->setFocus();
}
void clearTerminal()
{
// 清空输入框和输出窗口
inputLineEdit->clear();
outputTextEdit->clear();
// 设置焦点到输入框
inputLineEdit->setFocus();
}
private:
QPlainTextEdit *outputTextEdit;
QLineEdit *inputLineEdit;
QPushButton *clearButton;
QStringList commandHistory;
int historyIndex = 0;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TerminalWidget terminal;
terminal.show();
return app.exec();
}