当前位置:网站首页>QT database realizes page turning function

QT database realizes page turning function

2022-06-12 14:19:00 silence_ heart

qt Use qsqltablemodel and tableview Control to operate and display the database , however qsqltablemodel Page flipping is not supported by itself .
however qsqltablemodel Of select Function will call selectStatement Statement returned by function , Query the database , That is, you can inherit qsqltablemodel class , Override the selectStatement Function to display a specific number of pages of data
Custom class mySqlTableModel Inherit qsqltablemodel

class mySqlTableModel : public QSqlTableModel
{
public:
    mySqlTableModel();
    QString selectStatement() const;
    void totalRowCount();
    void setSelectAllData(bool choose);
private:
    int totalRows;
    int currentPage;
    bool selectAllData;
};

overwrite selectStatement function

QString mySqlTableModel::selectStatement()const{
    QString strRet;
    if(selectAllData){
        return this->QSqlTableModel::selectStatement();
    }else{
        strRet+="select * from table_1 limit 5 offset "+QString::number((currentPage-1)*5);
    }
    return strRet;
}

Why add one selectAllData Variable , because QSqlTableModel Of filter The function will also use selectStatement function , To query the integrity of data , In the use of filter Function will selectAllData Assignment true , Use native selectStatement function
Statistics of the total number of rows

void mySqlTableModel::totalRowCount(){
    QSqlQuery query;
    query.exec("select * from table_1");
    QSqlQueryModel *querymodel=new QSqlQueryModel();
    querymodel->setQuery(query);
    totalRows=querymodel->rowCount();
}

mySqlTableModel Page up and page down functions

// Page down 
bool mySqlTableModel::pageDown(){
    if(totalRows>currentPage*5){
        currentPage++;
        return true;
    }
    return false;
}
// Page up 
bool mySqlTableModel::pageUp(){
    if(currentPage>1){
        currentPage--;
        return true;
    }
    return false;
}

The main program uses mySqlTableModel Turn pages (model by mySqlTableModel Example )

// Page down 
void MainWindow::on_pushButton_3_clicked()
{
    model->pageDown();
    model->setSelectAllData(false);
    model->select();

}
// Page up 
void MainWindow::on_pushButton_2_clicked()
{
    model->pageUp();
    model->setSelectAllData(false);
    model->select();
}
原网站

版权声明
本文为[silence_ heart]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010512423597.html