Qt數據庫翻頁Demo

引言

 當數據庫記錄數很多的時候,如果將它全部顯示到一個視圖(view)中,長長的滾輪,拖動看起來會很累。這個時候給數據表加一個翻頁的功能,每頁限制顯示一定數量的記錄,這樣會顯得更合理一點。
 於是我這邊就寫了個小Demo,用來實現一個簡易的翻頁功能。

效果

result

思路

 主要用了SQL中的LIMIT項。

LIMIT簡單用法

 LIMIT子句用於對整個SELECT語句返回的行數設置限制。
 看下兩個小例子,
 篩選出數據表table1中前1000條記錄。

SELECT * FROM table1 LIMIT 1000;

 篩選出數據表table1中第1001條開始,後1000條記錄,即1001-2000條記錄。

SELECT * FROM table1 LIMIT 1000, 1000;

button配合SQL語句

 其實每個翻頁操作按鈕都對應SQL語句,看起來好像是單純的翻頁操作。

代碼

Demo鏈接

Demo鏈接
 提取碼:l9cc

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSqlQueryModel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

    void on_pushButton_prePage_clicked();

    void on_pushButton_nextPage_clicked();

    void on_pushButton_firstPage_clicked();

    void on_pushButton_lastPage_clicked();

    void upDatePageInfo();

    void on_pushButton_gotoPage_clicked();

private:
    Ui::MainWindow *ui;
    QSqlQueryModel *m_model;
    int m_nCurrentPage;
    int m_nPageCount;

};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTableView>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
/* 每頁顯示的行數 */
#define LINESPPAGE 1000

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_nCurrentPage = 1;
    m_model = new QSqlQueryModel;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    bool ok = db.open();
    if (!ok) qDebug()<<db.lastError();

    m_model->setQuery(QString("select * from TH015A limit 0, '%1'").arg(LINESPPAGE));

    m_model->setHeaderData(0, Qt::Horizontal, tr("時間"));
    m_model->setHeaderData(1, Qt::Horizontal, tr("壓力(KPa)"));
    m_model->setHeaderData(2, Qt::Horizontal, tr("密度(g/L)"));
    m_model->setHeaderData(3, Qt::Horizontal, tr("溫度(℃)"));
    m_model->setHeaderData(4, Qt::Horizontal, tr("地址"));

    QSqlQuery query("select * from TH015A");
    query.last();
    m_nPageCount = query.at()/LINESPPAGE + 1;
    ui->lineEdit_pageCount->setText(QString("共%1頁").arg(m_nPageCount));
    ui->lineEdit_currentPage->setText(QString("第%1頁").arg(m_nCurrentPage));

    ui->tableView->setModel(m_model);

}

MainWindow::~MainWindow()
{
    delete ui;
}

/* 上一頁 */
void MainWindow::on_pushButton_prePage_clicked()
{
    if (m_nCurrentPage <= 1)
    {
        return;
    }
    m_model->setQuery(QString("select * from TH015A limit '%1', '%2'").arg(LINESPPAGE*(m_nCurrentPage-2)).arg(LINESPPAGE));
    m_nCurrentPage--;
    upDatePageInfo();
}
/* 下一頁 */
void MainWindow::on_pushButton_nextPage_clicked()
{
    if (m_nCurrentPage >= m_nPageCount)
    {
        return;
    }
    m_model->setQuery(QString("select * from TH015A limit '%1', '%2'").arg(LINESPPAGE*m_nCurrentPage).arg(LINESPPAGE));
    m_nCurrentPage++;
    upDatePageInfo();
}
/* 首頁 */
void MainWindow::on_pushButton_firstPage_clicked()
{
    m_model->setQuery(QString("select * from TH015A limit '%1', '%2'").arg(LINESPPAGE*0).arg(LINESPPAGE));
    m_nCurrentPage = 1;
    upDatePageInfo();
}
/* 末頁 */
void MainWindow::on_pushButton_lastPage_clicked()
{
    m_model->setQuery(QString("select * from TH015A limit '%1', '%2'").arg(LINESPPAGE*(m_nPageCount-1)).arg(LINESPPAGE));
    m_nCurrentPage = m_nPageCount;
    upDatePageInfo();
}
/* 更新顯示頁 */
void MainWindow::upDatePageInfo()
{
    QSqlQuery query("select * from TH015A");
    query.last();
    m_nPageCount = query.at()/LINESPPAGE + 1;
    ui->lineEdit_pageCount->setText(QString("共%1頁").arg(m_nPageCount));
    ui->lineEdit_currentPage->setText(QString("第%1頁").arg(m_nCurrentPage));
}
/* 跳轉 */
void MainWindow::on_pushButton_gotoPage_clicked()
{
    int nPage = ui->lineEdit_gotoPage->text().toInt();
    m_model->setQuery(QString("select * from TH015A limit '%1', '%2'").arg(LINESPPAGE*(nPage-1)).arg(LINESPPAGE));
    m_nCurrentPage = nPage;
    upDatePageInfo();
}

mainwindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>799</width>
    <height>497</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QHBoxLayout" name="horizontalLayout_2">
    <item>
     <widget class="QTableView" name="tableView"/>
    </item>
    <item>
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QPushButton" name="pushButton_prePage">
        <property name="text">
         <string>上一頁</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton_nextPage">
        <property name="text">
         <string>下一頁</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton_firstPage">
        <property name="text">
         <string>首頁</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton_lastPage">
        <property name="text">
         <string>尾頁</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QGroupBox" name="groupBox_gotoPage">
        <property name="title">
         <string/>
        </property>
        <layout class="QGridLayout" name="gridLayout">
         <item row="0" column="0">
          <widget class="QPushButton" name="pushButton_gotoPage">
           <property name="text">
            <string>跳轉</string>
           </property>
          </widget>
         </item>
         <item row="0" column="1">
          <widget class="QLineEdit" name="lineEdit_gotoPage">
           <property name="sizePolicy">
            <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
             <horstretch>0</horstretch>
             <verstretch>0</verstretch>
            </sizepolicy>
           </property>
          </widget>
         </item>
        </layout>
       </widget>
      </item>
      <item>
       <widget class="QLineEdit" name="lineEdit_currentPage">
        <property name="sizePolicy">
         <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="readOnly">
         <bool>true</bool>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QLineEdit" name="lineEdit_pageCount">
        <property name="sizePolicy">
         <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="readOnly">
         <bool>true</bool>
        </property>
       </widget>
      </item>
      <item>
       <spacer name="verticalSpacer">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>40</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>799</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

.pro

#-------------------------------------------------
#
# Project created by QtCreator 2020-01-03T10:41:04
#
#-------------------------------------------------

QT       += core gui sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = sqlPage
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

總結

 在對較大的數據量進行操作的時候,時間和空間資源都會消耗較大,尤其是空間,拿本例來說,如果數據量特別大,你需要在程序中用較大的空間去臨時存儲,才能做到篩選數據顯示。
 本例中用時間置換了空間,使每次翻頁操作的執行都要重新查詢數據庫,來替代程序中大數據存儲。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章