分页算法:在QTableView中实现分页算法,代c++代码怎么写

在这里插入图片描述

#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>
#include <QHeaderView>

class PagingModel : public QStandardItemModel {
    Q_OBJECT
public:
    PagingModel(int rows, int columns, int pageSize, QObject *parent = nullptr)
        : QStandardItemModel(rows, columns, parent), m_pageSize(pageSize), m_currentPage(0) {}

    int rowCount(const QModelIndex &parent = QModelIndex()) const override {
        if (parent.isValid()) return 0; // Inherited from QAbstractItemModel
        return (m_data.size() + m_pageSize - 1) / m_pageSize; // Page count
    }

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override {
        if (!index.isValid() || index.row() >= rowCount() || index.column() >= columnCount())
            return QVariant();

        int row = index.row() * m_pageSize + index.column();
        if (row >= m_data.size()) return QVariant();

        if (role == Qt::DisplayRole) {
            return m_data[row];
        } else {
            return QVariant();
        }
    }

    void setCurrentPage(int page) {
        if (page >= 0 && page < rowCount()) {
            m_currentPage = page;
            emit layoutChanged(); // Notify the view to update
        }
    }

private:
    int m_pageSize;
    int m_currentPage;
    QVector<QString> m_data; // Example data storage
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // Create a custom model with 100 rows and 5 columns, 10 items per page
    PagingModel model(100, 5, 10);
    // Populate the model with example data
    for (int i = 0; i < 100; ++i) {
        model.setData(model.index(i, 0), QString("Row %1").arg(i));
    }

    // Create a table view and set the model
    QTableView view;
    view.setModel(&model);
    view.horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    view.show();

    // Connect the currentPageChanged signal to a slot that updates the view's current page
    QObject::connect(&model, &PagingModel::layoutChanged, [&]() {
        view.scrollToTop(); // Scroll to the top of the new page
    });

    return app.exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值