代码如下:
#include <QMainWindow>
#include <QWidget>
#include <QPushButton>
#include <QStackedWidget>
#include <QToolBar>
#include <QAction>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void forward();
void backward();
void openFile();
void saveFile();
void closeFile();
private:
int currentPageIndex;
int maxPageIndex;
QStackedWidget* stackedWidget;
QToolBar* toolBar;
QAction* forwardAction;
QAction* backwardAction;
// 一些用于演示的假文件内容,实际应该使用 QFile 进行读写
QStringList fileContents;
void addPage(const QString& content);
};
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 初始化历史记录相关变量
currentPageIndex = 0;
maxPageIndex = -1;
// 初始化工具栏和动作
toolBar = new QToolBar(this);
forwardAction = new QAction("Forward", this);
backwardAction = new QAction("Backward", this);
toolBar->addAction(backwardAction);
toolBar->addAction(forwardAction);
addToolBar(toolBar);
// 设置信号槽连接
connect(forwardAction, &QAction::triggered, this, &MainWindow::forward);
connect(backwardAction, &QAction::triggered, this, &MainWindow::backward);
// 新建一个 QStackedWidget 并添加到主界面中
stackedWidget = new QStackedWidget(this);
setCentralWidget(stackedWidget);
// 添加初始页面
fileContents << "Page 1" << "Page 2" << "Page 3" << "Page 4" << "Page 5";
for (const QString& content : fileContents) {
addPage(content);
}
// 设置窗口标题和大小
setWindowTitle("File History");
resize(400, 300);
}
MainWindow::~MainWindow()
{
}
void MainWindow::forward()
{
if (currentPageIndex < maxPageIndex) {
currentPageIndex++;
stackedWidget->setCurrentIndex(currentPageIndex);
backwardAction->setEnabled(true);
if (currentPageIndex == maxPageIndex) {
forwardAction->setEnabled(false);
}
}
}
void MainWindow::backward()
{
if (currentPageIndex > 0) {
currentPageIndex--;
stackedWidget->setCurrentIndex(currentPageIndex);
forwardAction->setEnabled(true);
if (currentPageIndex == 0) {
backwardAction->setEnabled(false);
}
}
}
void MainWindow::openFile()
{
// 实现文件打开逻辑
}
void MainWindow::saveFile()
{
// 实现文件保存逻辑
}
void MainWindow::closeFile()
{
// 清空历史记录
stackedWidget->clear();
currentPageIndex = 0;
maxPageIndex = -1;
// 关闭文件
}
void MainWindow::addPage(const QString& content)
{
if (maxPageIndex >= 19) {
// 历史记录最多存20页,超出则删除最老的一页
stackedWidget->removeWidget(stackedWidget->widget(0));
currentPageIndex--;
maxPageIndex--;
}
// 创建新的页面并添加到 Stack Widget 中
QWidget* page = new QWidget(this);
QPushButton* button = new QPushButton(content, page);
button->move(50, 50);
stackedWidget->addWidget(page);
// 更新历史记录相关变量
currentPageIndex++;
maxPageIndex = currentPageIndex;
stackedWidget->setCurrentIndex(currentPageIndex);
backwardAction->setEnabled(true);
forwardAction->setEnabled(false);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}