QT开发中文网

Qt 存储历史界面,最多存20页,通过按下键盘的“前进”和“后退”按钮来实现界面的多次前进和多次返回功能,文件关闭后清空历史记录C++

可以使用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;
};

使用方法:

  1. 创建一个HistoryWidget对象,将其添加到主窗口中。
  2. 监听pageOpened信号,在页面加载完成时调用openPage函数添加到历史记录中。
  3. 当用户按下“前进”或“后退”按钮时,监听pageOpened信号并更新当前页面内容即可。

关闭程序时可以在析构函数中清空历史记录:

HistoryWidget::~HistoryWidget() {
    history.clear();
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=855

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?