可以使用QList来存储历史页面,每次打开文件时将页面加入列表尾部,按下“前进”按钮时取出列表尾部的页面并显示,然后将其移到列表头部;按下“后退”按钮时取出列表头部的页面并显示,然后将其移到列表尾部。使用QListIterator可以方便地遍历列表。
以下是一个简单的示例代码:
#include <QtWidgets>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow() {
// 创建工具栏和按钮
QToolBar *toolbar = new QToolBar(this);
QAction *backAction = toolbar->addAction("后退");
QAction *forwardAction = toolbar->addAction("前进");
connect(backAction, &QAction::triggered, this, &MainWindow::goBack);
connect(forwardAction, &QAction::triggered, this, &MainWindow::goForward);
addToolBar(toolbar);
// 创建文本编辑器
editor = new QTextEdit(this);
setCentralWidget(editor);
// 初始化历史记录
history.append("");
current = 0;
}
private slots:
void goBack() {
if (current > 0) {
current--;
editor->setPlainText(history[current]);
}
}
void goForward() {
if (current < history.size() - 1) {
current++;
editor->setPlainText(history[current]);
}
}
protected:
void closeEvent(QCloseEvent *event) override {
// 关闭程序时清空历史记录
history.clear();
event->accept();
}
void keyPressEvent(QKeyEvent *event) override {
// 按下Ctrl+Z时模拟后退按钮
if (event->key() == Qt::Key_Z && event->modifiers() == Qt::ControlModifier) {
goBack();
}
// 按下Ctrl+Y时模拟前进按钮
else if (event->key() == Qt::Key_Y && event->modifiers() == Qt::ControlModifier) {
goForward();
}
else {
QMainWindow::keyPressEvent(event);
}
}
void openFile(const QString &fileName) override {
// 打开文件时更新历史记录
history.append(editor->toPlainText());
current = history.size() - 1;
QMainWindow::openFile(fileName);
}
private:
QTextEdit *editor;
QList<QString> history;
int current;
};
在该示例中,我们重载了MainWindow的closeEvent和keyPressEvent函数,在关闭程序时清空历史记录,在按下Ctrl+Z和Ctrl+Y键时模拟后退和前进按钮。当打开文件时,将当前页面加入历史记录并更新current变量,以便实现多次前进和多次返回功能。