#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();
}