可以使用QStack类来实现历史记录功能,每次打开一个新页面时将其加入栈顶;当用户按下“前进”按钮时,从栈中弹出一个页面并显示;当用户按下“后退”按钮时,将当前页面压入栈中,并弹出栈顶的页面进行显示。
以下是示例代码:
#include <QtWidgets>
const int MAX_HISTORY_SIZE = 20;
class HistoryWidget : public QWidget {
public:
explicit HistoryWidget(QWidget *parent = nullptr) :
QWidget(parent), backBtn("<"), forwardBtn(">"), currentIndex(-1)
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(&backBtn);
layout->addWidget(&forwardBtn);
connect(&backBtn, SIGNAL(clicked()), this, SLOT(goBack()));
connect(&forwardBtn, SIGNAL(clicked()), this, SLOT(goForward()));
}
void openPage(const QString &url) {
// Add a new page to the history stack
if (history.size() > MAX_HISTORY_SIZE) {
history.removeFirst(); // Remove oldest page if maximum size is reached
}
if (currentIndex + 1 < history.size()) {
history.resize(currentIndex + 1); // Discard any pages after the current one
}
history.append(url);
currentIndex++;
// Update button states
backBtn.setEnabled(currentIndex > 0);
forwardBtn.setEnabled(currentIndex < history.size() - 1);
emit pageOpened(url);
}
signals:
void pageOpened(const QString &url);
private slots:
void goBack() {
if (currentIndex > 0) {
currentIndex--;
emit pageOpened(history[currentIndex]);
}
updateButtonStates();
}
void goForward() {
if (currentIndex < history.size() - 1) {
currentIndex++;
emit pageOpened(history[currentIndex]);
}
updateButtonStates();
}
private:
void updateButtonStates() {
backBtn.setEnabled(currentIndex > 0);
forwardBtn.setEnabled(currentIndex < history.size() - 1);
}
QList<QString> history;
QPushButton backBtn, forwardBtn;
int currentIndex;
};
使用方法:
- 创建一个
HistoryWidget
对象,将其添加到主窗口中。 - 监听
pageOpened
信号,在页面加载完成时调用openPage
函数添加到历史记录中。 - 当用户按下“前进”或“后退”按钮时,监听
pageOpened
信号并更新当前页面内容即可。
关闭程序时可以在析构函数中清空历史记录:
HistoryWidget::~HistoryWidget() {
history.clear();
}