├── DatabaseManager.cpp ├── DatabaseManager.h ├── GlobalConstances.h ├── InsertDialog.cpp ├── InsertDialog.h ├── InsertDialog.ui ├── MainWindow.cpp ├── MainWindow.h ├── MainWindow.ui ├── README.md ├── SqlTableModel.cpp ├── SqlTableModel.h ├── TableViewPage.cpp ├── TableViewPage.h ├── TableViewPaging.pro ├── main.cpp └── screenshot.jpg /DatabaseManager.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #include "DatabaseManager.h" 18 | #include "GlobalConstances.h" 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | 26 | DatabaseManager::DatabaseManager(QObject *parent) : 27 | QObject(parent), 28 | m_status(Read) 29 | { 30 | } 31 | 32 | // 这里使用的是 SQLITECIPHER 数据库驱动, 33 | // 如果使用的是Qt自带默认的SQlite数据库,则修改这里的 34 | // 数据库驱动名为SQLITE,否则不能正常使用数据库引擎 35 | bool DatabaseManager::createConnect() 36 | { 37 | switch( m_status ) 38 | { 39 | case Read: 40 | { 41 | if(QSqlDatabase::contains("READ")) 42 | m_db = QSqlDatabase::database("READ"); 43 | else 44 | { 45 | m_db = QSqlDatabase::addDatabase("QSQLITE", "READ"); 46 | m_db.setDatabaseName(g_dbFileName); 47 | } 48 | }; 49 | break; 50 | case Write: 51 | { 52 | if(QSqlDatabase::contains("WRITE")) 53 | m_db = QSqlDatabase::database("WRITE"); 54 | else 55 | { 56 | m_db = QSqlDatabase::addDatabase("QSQLITE", "WRITE"); 57 | m_db.setDatabaseName(g_dbFileName); 58 | } 59 | }; 60 | break; 61 | } 62 | 63 | if( !m_db.isOpen() ) 64 | { 65 | if ( !m_db.open() ) 66 | { 67 | qDebug()<< QString(" can't open database >>>>>> data.sqlite"); 68 | qDebug() << "error code: " << m_db.lastError(); 69 | return false; 70 | } 71 | } 72 | 73 | return true; 74 | } 75 | 76 | bool DatabaseManager::createTable() 77 | { 78 | QStringList tableList = m_db.tables(); 79 | QSqlQuery query(m_db); 80 | if( !tableList.contains(g_dbTableName) ) 81 | { 82 | QString createTable = QString("CREATE TABLE %1 (ID integer PRIMARY KEY AUTOINCREMENT," 83 | "Checked integer default 0, Title text, Date text, Weather text, Author text, Content text)" 84 | ).arg(g_dbTableName); 85 | if(!query.exec(createTable)) 86 | { 87 | QMessageBox::warning(0, QObject::tr("Create table error"), QObject::tr("Error: ")+ query.lastError().text(), QMessageBox::Ok); 88 | qDebug()<< "Create table error: " << query.lastError(); 89 | return false; 90 | } 91 | } 92 | 93 | return true; 94 | } 95 | -------------------------------------------------------------------------------- /DatabaseManager.h: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #ifndef DATABASEMANAGER_H 18 | #define DATABASEMANAGER_H 19 | 20 | #include 21 | #include 22 | 23 | class DatabaseManager : public QObject 24 | { 25 | Q_OBJECT 26 | public: 27 | enum Status 28 | { 29 | Read, 30 | Write 31 | }; 32 | 33 | explicit DatabaseManager(QObject *parent = 0); 34 | bool createConnect(); 35 | bool createTable(); 36 | 37 | inline QSqlDatabase database() const { return m_db; } 38 | Status status() const { return m_status; } 39 | void setStatus(DatabaseManager::Status status = Read) { m_status = status; } 40 | 41 | signals: 42 | 43 | public slots: 44 | 45 | private: 46 | QSqlDatabase m_db; 47 | Status m_status; 48 | }; 49 | 50 | #endif // DATABASEMANAGER_H 51 | -------------------------------------------------------------------------------- /GlobalConstances.h: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #ifndef GLOBALCONSTANCES_H 18 | #define GLOBALCONSTANCES_H 19 | 20 | #include 21 | static const QString g_dbFileName = "data.dat"; 22 | static const QString g_dbTableName = "daily"; 23 | 24 | static const QString g_titleLabel = "Title"; 25 | static const QString g_dateLabel = "Date"; 26 | static const QString g_authorLabel = "Author"; 27 | static const QString g_weatherLabel = "Weather"; 28 | static const QString g_contentLabel = "Content"; 29 | 30 | #define CHECKED 1 31 | #define TITLE 2 32 | #define DATE 3 33 | #define WEATHER 4 34 | #define AUTHOR 5 35 | #define CONTENT 6 36 | 37 | #endif // GLOBALCONSTANCES_H 38 | 39 | -------------------------------------------------------------------------------- /InsertDialog.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #include "InsertDialog.h" 18 | #include "ui_InsertDialog.h" 19 | 20 | InsertDialog::InsertDialog(QWidget *parent) : 21 | QDialog(parent), 22 | ui(new Ui::InsertDialog) 23 | { 24 | ui->setupUi(this); 25 | 26 | connect(this, SIGNAL(accepted()), 27 | this, SLOT(submite()) ); 28 | } 29 | 30 | InsertDialog::~InsertDialog() 31 | { 32 | delete ui; 33 | } 34 | 35 | void InsertDialog::initInfo(const QList &list) 36 | { 37 | ui->titleEdt->setText(list.at(0).toString()); 38 | // QDateTime date = QDateTime::fromString(list.at(1).toString()); 39 | // ui->dateEdit->setDateTime(date); 40 | ui->dateEdit->setDateTime(QDateTime::currentDateTime()); 41 | ui->weatherEdt->setText(list.at(2).toString()); 42 | ui->authorEdt->setText(list.at(3).toString()); 43 | ui->contentEdt->setPlainText(list.at(4).toString()); 44 | } 45 | 46 | void InsertDialog::submite() 47 | { 48 | QList list; 49 | QString title = ui->titleEdt->text(); 50 | QString date = ui->dateEdit->text(); 51 | QString weather = ui->weatherEdt->text(); 52 | QString author = ui->authorEdt->text(); 53 | QString content = ui->contentEdt->toPlainText(); 54 | list << title << date << weather << author << content; 55 | 56 | emit accepted(list); 57 | } 58 | -------------------------------------------------------------------------------- /InsertDialog.h: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #ifndef INSERTDIALOG_H 18 | #define INSERTDIALOG_H 19 | 20 | #include 21 | 22 | namespace Ui { 23 | class InsertDialog; 24 | } 25 | 26 | class InsertDialog : public QDialog 27 | { 28 | Q_OBJECT 29 | 30 | public: 31 | explicit InsertDialog(QWidget *parent = 0); 32 | ~InsertDialog(); 33 | void initInfo(const QList &list); 34 | 35 | signals: 36 | void accepted( const QList & ); 37 | 38 | private slots: 39 | void submite(); 40 | 41 | private: 42 | Ui::InsertDialog *ui; 43 | }; 44 | 45 | #endif // INSERTDIALOG_H 46 | -------------------------------------------------------------------------------- /InsertDialog.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | InsertDialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 401 10 | 427 11 | 12 | 13 | 14 | Dialog 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Qt::Horizontal 24 | 25 | 26 | QDialogButtonBox::Cancel|QDialogButtonBox::Ok 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | Title: 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | Date: 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | Weather: 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | Author: 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | Content: 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | buttonBox 91 | accepted() 92 | InsertDialog 93 | accept() 94 | 95 | 96 | 248 97 | 254 98 | 99 | 100 | 157 101 | 274 102 | 103 | 104 | 105 | 106 | buttonBox 107 | rejected() 108 | InsertDialog 109 | reject() 110 | 111 | 112 | 316 113 | 260 114 | 115 | 116 | 286 117 | 274 118 | 119 | 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /MainWindow.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #include "MainWindow.h" 18 | #include "ui_MainWindow.h" 19 | #include "InsertDialog.h" 20 | 21 | MainWindow::MainWindow(QWidget *parent) : 22 | QMainWindow(parent), 23 | ui(new Ui::MainWindow) 24 | { 25 | ui->setupUi(this); 26 | updateCtrl(); 27 | 28 | QStringList pages; 29 | int totalPage = ui->tableView->totalPage(); 30 | for( int i = 1; i <= totalPage; ++i) 31 | pages.append( QString("%1").arg(i) ); 32 | ui->gotoPageBox->addItems(pages); 33 | 34 | connect(ui->tableView, SIGNAL(insertAct()), this, SLOT(insert()) ); 35 | connect(ui->tableView, SIGNAL(removeAct()), this, SLOT(remove()) ); 36 | connect(ui->highlightBtn, SIGNAL(clicked(bool)), ui->tableView, SLOT(highLightView(bool)) ); 37 | 38 | connect(ui->prePageBtn, SIGNAL(clicked()), this, SLOT(prevPage()) ); 39 | connect(ui->nextPageBtn, SIGNAL(clicked()), this, SLOT(nextPage()) ); 40 | // connect(ui->gotoPageBtn, SIGNAL(clicked()), this, SLOT(gotoPage()) ); 41 | connect(ui->gotoPageBox, SIGNAL(currentIndexChanged(int)), 42 | this, SLOT(gotoPage(int)) ); 43 | } 44 | 45 | MainWindow::~MainWindow() 46 | { 47 | delete ui; 48 | } 49 | 50 | void MainWindow::updateCtrl() 51 | { 52 | int total = ui->tableView->totalSize(); 53 | ui->totalLabel->setText( tr("Total %1").arg(total) ); 54 | 55 | int curPage = ui->tableView->currentPage(); 56 | int totalPage = ui->tableView->totalPage(); 57 | ui->curPageLabel->setText( tr("Page %1/%2").arg(curPage).arg(totalPage)); 58 | 59 | ui->nextPageBtn->setEnabled(true); 60 | ui->prePageBtn->setEnabled(true); 61 | 62 | if (curPage >= totalPage) 63 | ui->nextPageBtn->setEnabled(false); 64 | else if( curPage <= 1) 65 | ui->prePageBtn->setEnabled(false); 66 | else 67 | ; 68 | } 69 | 70 | void MainWindow::insert() 71 | { 72 | InsertDialog* insertDlg = new InsertDialog(this); 73 | QList infos = ui->tableView->currentRowInfo(); 74 | if( infos.count() >= 5) 75 | insertDlg->initInfo(infos); 76 | 77 | connect(insertDlg, SIGNAL(accepted(QList)), 78 | ui->tableView, SLOT(insert(QList)) ); 79 | int ok = insertDlg->exec(); 80 | if( ok ) 81 | { 82 | updateCtrl(); 83 | } 84 | insertDlg->deleteLater(); 85 | 86 | int totalPage = ui->tableView->totalPage(); 87 | int count = ui->gotoPageBox->count(); 88 | if( count < totalPage) 89 | { 90 | ui->gotoPageBox->addItem(QString("%1").arg(count+1)); 91 | } 92 | } 93 | 94 | void MainWindow::remove() 95 | { 96 | ui->tableView->remove(); 97 | updateCtrl(); 98 | int totalPage = ui->tableView->totalPage(); 99 | 100 | int count = ui->gotoPageBox->count(); 101 | if( count > totalPage) 102 | { 103 | ui->gotoPageBox->removeItem(count-1); 104 | } 105 | } 106 | 107 | void MainWindow::gotoPage(int index) 108 | { 109 | index++; 110 | ui->tableView->gotoPage(index); 111 | updateCtrl(); 112 | } 113 | 114 | void MainWindow::nextPage() 115 | { 116 | ui->tableView->nextPage(); 117 | updateCtrl(); 118 | } 119 | 120 | void MainWindow::prevPage() 121 | { 122 | ui->tableView->previousPage(); 123 | updateCtrl(); 124 | } 125 | -------------------------------------------------------------------------------- /MainWindow.h: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #ifndef MAINWINDOW_H 18 | #define MAINWINDOW_H 19 | 20 | #include 21 | 22 | namespace Ui { 23 | class MainWindow; 24 | } 25 | 26 | class MainWindow : public QMainWindow 27 | { 28 | Q_OBJECT 29 | 30 | public: 31 | explicit MainWindow(QWidget *parent = 0); 32 | ~MainWindow(); 33 | void updateCtrl(); 34 | 35 | private slots: 36 | void insert(); 37 | void remove(); 38 | void gotoPage(int index); 39 | void nextPage(); 40 | void prevPage(); 41 | 42 | private: 43 | Ui::MainWindow *ui; 44 | }; 45 | 46 | #endif // MAINWINDOW_H 47 | -------------------------------------------------------------------------------- /MainWindow.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 603 10 | 429 11 | 12 | 13 | 14 | MainWindow 15 | 16 | 17 | 18 | 19 | 20 | 21 | Qt::Horizontal 22 | 23 | 24 | 25 | 40 26 | 20 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | QAbstractItemView::SingleSelection 35 | 36 | 37 | QAbstractItemView::SelectItems 38 | 39 | 40 | false 41 | 42 | 43 | true 44 | 45 | 46 | 47 | 48 | 49 | 50 | Highlight 51 | 52 | 53 | true 54 | 55 | 56 | true 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | Total 0 66 | 67 | 68 | 69 | 70 | 71 | 72 | Qt::Horizontal 73 | 74 | 75 | QSizePolicy::Fixed 76 | 77 | 78 | 79 | 20 80 | 20 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | Page 0/0 89 | 90 | 91 | 92 | 93 | 94 | 95 | Pre page 96 | 97 | 98 | 99 | 100 | 101 | 102 | Next page 103 | 104 | 105 | 106 | 107 | 108 | 109 | Qt::Horizontal 110 | 111 | 112 | QSizePolicy::Fixed 113 | 114 | 115 | 116 | 20 117 | 20 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | Goto page: 126 | 127 | 128 | 129 | 130 | 131 | 132 | true 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 0 144 | 0 145 | 603 146 | 23 147 | 148 | 149 | 150 | 151 | 152 | TopToolBarArea 153 | 154 | 155 | false 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | TableViewPage 164 | QTableView 165 |
TableViewPage.h
166 |
167 |
168 | 169 | 170 |
171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TableViewPaging 2 |

QTableView和SQLite数据库分页方式显示数据

3 | 0.支持数据条目分页
4 | 1.支持页数跳转
5 | 2.使用model-delegate代理方式显示数据样式(表格颜色、字体颜色)
6 | 3.可插入/删除数据条目
7 | 4.显示数据分数和总条目
8 | ![image](screenshot.jpg) 9 | -------------------------------------------------------------------------------- /SqlTableModel.cpp: -------------------------------------------------------------------------------- 1 | #include "SqlTableModel.h" 2 | #include "GlobalConstances.h" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db) : 9 | QSqlTableModel(parent, db) 10 | { 11 | m_id = 0; 12 | m_nStartId = -1; 13 | m_nCurPageCount = 0; 14 | m_nAPageCount = 6; 15 | m_nTotal = 0; 16 | } 17 | 18 | QVariant SqlTableModel::headerData(int section, Qt::Orientation orientation, int role) const 19 | { 20 | if ( orientation == Qt::Vertical && role == Qt::DisplayRole ) 21 | return section + m_id; 22 | 23 | return QSqlTableModel::headerData(section, orientation, role); 24 | } 25 | 26 | int SqlTableModel::rowCount(const QModelIndex &parent) 27 | { 28 | return QSqlTableModel::rowCount(parent); 29 | } 30 | 31 | void SqlTableModel::previousPage() 32 | { 33 | if(m_nStartId <= 0 || m_nTotal <= 0) 34 | return; 35 | 36 | m_nCurPageCount = m_nAPageCount; 37 | m_nStartId -= m_nAPageCount; 38 | 39 | this->updateModel(); 40 | } 41 | 42 | void SqlTableModel::nextPage() 43 | { 44 | if( m_nCurPageCount < m_nAPageCount || m_nTotal <= 0) 45 | return; 46 | 47 | m_nStartId += m_nAPageCount; 48 | m_nCurPageCount = m_nTotal - m_nStartId > m_nAPageCount ? m_nAPageCount : m_nTotal - m_nStartId; 49 | 50 | this->updateModel(); 51 | } 52 | 53 | void SqlTableModel::gotoPage(int index) 54 | { 55 | if( index < m_nAPageCount || m_nTotal <= 0) 56 | return; 57 | 58 | m_nCurPageCount = m_nTotal % m_nAPageCount; 59 | m_nStartId = m_nTotal - index; 60 | 61 | this->updateModel(); 62 | } 63 | 64 | void SqlTableModel::updateModel() 65 | { 66 | m_nTotal = rowCount(); 67 | m_nCurPageCount = m_nTotal > m_nAPageCount ? m_nAPageCount : m_nTotal; 68 | 69 | QString strFilter = QString(" 1=1 limit %1,%2").arg(m_nStartId).arg(m_nAPageCount); 70 | this->setId(m_nStartId+1); 71 | this->setFilter(strFilter); 72 | this->select(); 73 | } 74 | -------------------------------------------------------------------------------- /SqlTableModel.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yuriyoung/TableViewPaging/6cd9e1efbe26f48221c9ac9d09b2bb88e3c0b2e1/SqlTableModel.h -------------------------------------------------------------------------------- /TableViewPage.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #include "TableViewPage.h" 18 | #include "DatabaseManager.h" 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | 31 | TableViewPage::TableViewPage(QWidget *parent) : 32 | QTableView(parent), 33 | m_nStartId(0), m_nPageSize(9), m_nCurPageSize(0), m_nTotal(0), 34 | m_nCurPage(1), m_nTotalPage(0) 35 | { 36 | DatabaseManager *dbMgr = new DatabaseManager; 37 | dbMgr->createConnect(); 38 | dbMgr->createTable(); 39 | dbMgr->setStatus(DatabaseManager::Read); 40 | QSqlDatabase db = dbMgr->database(); 41 | 42 | // initialize view 43 | m_sqlModel = new SqlTableModel(0, db); 44 | m_sqlModel->moveToThread(&m_thread); 45 | m_thread.start(); 46 | m_sqlModel->setTable(g_dbTableName); 47 | // m_model->setEditStrategy(QSqlTableModel::OnManualSubmit); 48 | m_sqlModel->select(); 49 | m_sqlModel->setHeaderData(CHECKED, Qt::Horizontal, tr("√")); 50 | m_sqlModel->setHeaderData(TITLE, Qt::Horizontal, tr("Title")); 51 | m_sqlModel->setHeaderData(DATE, Qt::Horizontal, tr("Date")); 52 | m_sqlModel->setHeaderData(WEATHER, Qt::Horizontal, tr("Weather")); 53 | m_sqlModel->setHeaderData(AUTHOR, Qt::Horizontal, tr("Author")); 54 | m_sqlModel->setHeaderData(CONTENT, Qt::Horizontal, tr("Content")); 55 | 56 | qDebug() << "row count:" << m_sqlModel->rowCount(); 57 | m_nTotal = m_sqlModel->rowCount(); 58 | m_nTotalPage = totalPage(); 59 | m_nLastPageSize = lastPageSize(); 60 | this->updateModel(); //更新每页数据 61 | this->setModel(m_sqlModel); 62 | this->hideColumn(0); 63 | this->verticalHeader()->hide(); 64 | 65 | this->setItemDelegate(new BackgroundItemDelegate(this)); 66 | } 67 | 68 | TableViewPage::~TableViewPage() 69 | { 70 | m_sqlModel->submitAll(); 71 | if(m_thread.isRunning()) 72 | { 73 | m_thread.quit(); 74 | m_thread.wait(); 75 | } 76 | m_sqlModel->clear(); 77 | m_sqlModel->deleteLater(); 78 | } 79 | 80 | /** 81 | * 当前选中行的所有列的数据,在添加新记录条时, 82 | * 从当前选中的行数据中,取默认数据到添加记录对话框中 83 | * @brief TableViewPage::currentRowInfo 84 | * @return 85 | */ 86 | QList TableViewPage::currentRowInfo() const 87 | { 88 | QList list; 89 | QModelIndex idx = this->currentIndex(); 90 | if( !idx.isValid() ) return list; 91 | int r = idx.row(); 92 | QSqlRecord record = m_sqlModel->record(r); //取得当前行的数据集 93 | for( int i = TITLE; i < record.count(); ++i)//从Title位置开始取数据 94 | { 95 | QSqlField field = record.field(i); 96 | QString data = field.value().toString(); 97 | list.append(data); 98 | } 99 | 100 | return list; 101 | } 102 | 103 | void TableViewPage::insert(const QList &valueList) 104 | { 105 | int rowNum = m_sqlModel->rowCount(); 106 | if( lastPageSize() >= m_nPageSize ) 107 | { 108 | m_nTotalPage++; 109 | } 110 | m_nCurPage = m_nTotalPage; 111 | 112 | m_sqlModel->insertRow(rowNum); 113 | int col = CHECKED; 114 | m_sqlModel->setData(m_sqlModel->index(rowNum, col), 0); 115 | for( int i = 0; i < valueList.count(); ++i) 116 | { 117 | col++; 118 | QString data = valueList.at(i).toString(); 119 | m_sqlModel->setData(m_sqlModel->index(rowNum, col), data); 120 | } 121 | m_nTotal++; 122 | 123 | m_sqlModel->submitAll(); 124 | updateModel(); 125 | qDebug() << m_sqlModel->rowCount(); 126 | QModelIndex sel = this->model()->index(m_sqlModel->rowCount(), 1); 127 | this->setCurrentIndex(sel); 128 | } 129 | 130 | void TableViewPage::remove() 131 | { 132 | QModelIndexList idxList = this->selectionModel()->selectedIndexes(); 133 | 134 | QMap rowMap; 135 | foreach (QModelIndex index, idxList) 136 | rowMap.insert(index.row(), 0); 137 | 138 | int rowDel; 139 | QMapIterator rowMapIterator(rowMap); 140 | rowMapIterator.toBack(); 141 | while (rowMapIterator.hasPrevious()) 142 | { 143 | rowMapIterator.previous(); 144 | rowDel = rowMapIterator.key(); 145 | this->model()->removeRow(rowDel); 146 | } 147 | if( lastPageSize() <= 1 ) 148 | { 149 | m_nLastPageSize = m_nPageSize; 150 | m_nTotalPage--; 151 | m_nCurPage--; 152 | } 153 | m_nTotal--; 154 | m_sqlModel->submitAll(); 155 | 156 | updateModel(); 157 | } 158 | 159 | void TableViewPage::previousPage() 160 | { 161 | if(m_nStartId <= 0 || m_nTotal <= 0) 162 | return; 163 | 164 | m_nCurPage--; 165 | this->updateModel(); 166 | } 167 | 168 | void TableViewPage::nextPage() 169 | { 170 | if( m_nCurPage >= m_nTotalPage || m_nTotal <= 0) 171 | return; 172 | 173 | m_nCurPage++; 174 | this->updateModel(); 175 | } 176 | 177 | /** 178 | * 跳转到第 index 页 179 | * @brief TableViewPage::gotoPage 180 | * @param index 181 | */ 182 | void TableViewPage::gotoPage(int index) 183 | { 184 | if( index <= 0 || index > m_nTotalPage || m_nTotalPage <= 0 || index == m_nCurPage) 185 | return; 186 | 187 | m_nCurPage = index; 188 | this->updateModel(); 189 | } 190 | 191 | /** 192 | * 总页数 193 | * @brief TableViewPage::totalPage 194 | * @return 195 | */ 196 | int TableViewPage::totalPage() 197 | { 198 | m_nTotalPage = m_nTotal / m_nPageSize; 199 | m_nTotalPage = (m_nTotal % m_nPageSize) > 0 ? (m_nTotalPage + 1) : m_nTotalPage; 200 | 201 | return m_nTotalPage; 202 | } 203 | 204 | /** 205 | * 更新每页数据 206 | * @brief TableViewPage::updateModel 207 | */ 208 | void TableViewPage::updateModel() 209 | { 210 | m_sqlModel->submit(); 211 | m_nStartId = (m_nCurPage-1) * m_nPageSize; 212 | QString strFilter = QString(" 1=1 limit %1,%2").arg(m_nStartId).arg(m_nPageSize); 213 | m_sqlModel->setFilter(strFilter); 214 | m_sqlModel->select(); 215 | m_nCurPageSize = m_sqlModel->rowCount(); 216 | } 217 | 218 | void TableViewPage::highLightView(bool enabled) 219 | { 220 | if( enabled ) 221 | this->setItemDelegate(new BackgroundItemDelegate(this)); 222 | else 223 | this->setItemDelegate(new QItemDelegate(this)); 224 | } 225 | 226 | /** 227 | * 最后一页记录条数 228 | * @brief TableViewPage::lastPageSize 229 | * @return 230 | */ 231 | int TableViewPage::lastPageSize() 232 | { 233 | m_nLastPageSize = (m_nTotal % m_nPageSize) == 0 ? m_nPageSize : (m_nTotal % m_nPageSize); 234 | 235 | return m_nLastPageSize; 236 | } 237 | 238 | void TableViewPage::contextMenuEvent(QContextMenuEvent *event) 239 | { 240 | QMenu* popMenu = new QMenu(this); 241 | QAction *insertAction = popMenu->addAction( tr("&Insert") ); 242 | connect( insertAction, SIGNAL(triggered()), this, SIGNAL(insertAct()) ); 243 | 244 | QAction *removeAction = popMenu->addAction( tr("&Remove") ); 245 | removeAction->setEnabled(false); 246 | 247 | QModelIndex idx = this->indexAt( mapFromGlobal( QPoint( event->globalPos().x(), \ 248 | event->globalPos().y()-this->horizontalHeader()->height())) ); 249 | if( idx.isValid() ) 250 | { 251 | removeAction->setEnabled(true); 252 | connect( removeAction, SIGNAL(triggered()), this, SIGNAL(removeAct()) ); 253 | } 254 | else 255 | { 256 | this->clearSelection(); 257 | this->selectionModel()->clearSelection(); 258 | } 259 | 260 | popMenu->exec(event->globalPos()); 261 | event->accept(); 262 | } 263 | -------------------------------------------------------------------------------- /TableViewPage.h: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #ifndef TABLEVIEWPAGE_H 18 | #define TABLEVIEWPAGE_H 19 | #include "GlobalConstances.h" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include 35 | 36 | class QSqlDatabase; 37 | 38 | class SqlTableModel : public QSqlTableModel 39 | { 40 | Q_OBJECT 41 | public: 42 | explicit SqlTableModel(QWidget *parent = 0, QSqlDatabase db = QSqlDatabase()): 43 | QSqlTableModel(parent, db) 44 | { 45 | } 46 | 47 | Qt::ItemFlags flags( const QModelIndex &index ) const 48 | { 49 | if(!index.isValid()) 50 | return 0; 51 | 52 | if ( index.column() == CHECKED ) 53 | return (QSqlTableModel::flags(index) &~Qt::ItemIsEditable); 54 | 55 | return QSqlTableModel::flags(index); 56 | } 57 | 58 | bool setData( const QModelIndex &index, const QVariant &value, int role = Qt::EditRole ) 59 | { 60 | if(!index.isValid()) 61 | return false; 62 | 63 | if( index.column() != CHECKED ) 64 | { 65 | QSqlTableModel::setData(index, value, Qt::EditRole); 66 | return submit();//实时提交有些慢,退出时再提交 67 | } 68 | 69 | return QSqlTableModel::setData(index, value, Qt::EditRole); 70 | } 71 | 72 | QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const 73 | { 74 | if(!index.isValid()) 75 | return QVariant(); 76 | 77 | if (role == Qt::DisplayRole) 78 | { 79 | if ( index.column() == CHECKED ) 80 | { 81 | int checked = this->record(index.row()).value(CHECKED).toInt(); 82 | return checked;// == 1 ? Qt::Checked : Qt::Unchecked; 83 | } 84 | } 85 | 86 | return QSqlTableModel::data(index, role); 87 | } 88 | }; 89 | 90 | class TableViewPage : public QTableView 91 | { 92 | Q_OBJECT 93 | public: 94 | explicit TableViewPage(QWidget *parent = 0); 95 | ~TableViewPage(); 96 | 97 | // 为了获取被隐藏的列数据,直接从当前tableview的model是无法 98 | // 获取被隐藏列的数据的,只能通过数据库的model取得数据 99 | QSqlTableModel* sqlModel() { return m_sqlModel; } 100 | 101 | QList currentRowInfo() const; 102 | int currentPage() const { return m_nCurPage; } 103 | int totalSize() const { return m_nTotal; } 104 | int lastPageSize() const { return m_nLastPageSize; } 105 | 106 | signals: 107 | void insertAct(); 108 | void removeAct(); 109 | 110 | public slots: 111 | void insert(const QList &valueList); 112 | void remove(); 113 | 114 | void previousPage(); 115 | void nextPage(); 116 | void gotoPage(int index); 117 | int totalPage(); 118 | void updateModel(); 119 | 120 | void highLightView(bool); 121 | 122 | protected: 123 | void contextMenuEvent(QContextMenuEvent *event); 124 | 125 | private: 126 | int lastPageSize(); 127 | 128 | private: 129 | SqlTableModel* m_sqlModel; 130 | QThread m_thread; 131 | 132 | int m_nStartId; 133 | int m_nPageSize; 134 | int m_nCurPageSize; 135 | int m_nLastPageSize; 136 | int m_nTotal; 137 | 138 | int m_nCurPage; 139 | int m_nTotalPage; 140 | }; 141 | 142 | 143 | class BackgroundItemDelegate: public QItemDelegate 144 | { 145 | Q_OBJECT 146 | public: 147 | explicit BackgroundItemDelegate(QWidget* parent):QItemDelegate(parent){} 148 | 149 | void paint(QPainter *painter, const QStyleOptionViewItem &option, 150 | const QModelIndex &index ) const 151 | { 152 | // 得到index的文本,以便后面绘制 153 | QString text = (index.data(Qt::DisplayRole)).toString(); 154 | QStyleOptionViewItemV4 opt = setOptions(index, option); 155 | // 文本显示对齐方式 156 | // opt.displayAlignment = Qt::AlignHCenter | Qt::AlignVCenter;; 157 | 158 | qobject_cast(parent())->horizontalHeader()->resizeSection(CHECKED, 20); 159 | 160 | painter->save(); 161 | QPen pen; 162 | 163 | if( index.column() == CHECKED ) 164 | { 165 | painter->restore(); 166 | //获取值 167 | bool checked = index.model()->data(index, Qt::DisplayRole).toBool(); 168 | //按钮的风格选项 169 | QStyleOptionButton *checkOpt = new QStyleOptionButton(); 170 | checkOpt->state |= QStyle::State_Enabled; 171 | //根据值判断是否选中 172 | if(checked) 173 | { 174 | checkOpt->state |= QStyle::State_On; 175 | } 176 | else 177 | { 178 | checkOpt->state |= QStyle::State_Off; 179 | } 180 | //返回QCheckBox几何形状 181 | checkOpt->rect = CheckBoxRect(option); 182 | //绘制QCheckBox 183 | QApplication::style()->drawControl(QStyle::CE_CheckBox, checkOpt, painter); 184 | } 185 | // 绘制文本颜色 186 | else if(index.column() == TITLE) 187 | { 188 | // 第 1 列 绘制背景 189 | painter->fillRect(opt.rect, QBrush(QColor(22, 83, 134))); 190 | 191 | // 设置文本颜色画笔, 下同 192 | pen.setColor(QColor(200,106,123)); 193 | } 194 | else if(index.column() == DATE) 195 | { 196 | pen.setColor(QColor(200, 100, 140)); 197 | } 198 | else if(index.column() == WEATHER) 199 | { 200 | QString weather = qobject_cast(parent())-> 201 | sqlModel()->index(index.row(), WEATHER).data().toString(); 202 | if( weather == "晴" ) 203 | { 204 | pen.setColor(QColor(255,0,0)); 205 | // painter->fillRect(opt.rect, QBrush(QColor(120, 113, 34))); 206 | } 207 | else if(weather == "雨天") 208 | { 209 | pen.setColor(QColor(105,120,210)); 210 | } 211 | else if(weather == "阴天") 212 | { 213 | pen.setColor(QColor(100,100,100)); 214 | } 215 | else 216 | pen.setColor(QColor(140,200,25)); 217 | } 218 | else if(index.column() == AUTHOR) 219 | { 220 | pen.setColor(QColor(40,240,25)); 221 | QStyleOptionComboBox *comboboxOpt = new QStyleOptionComboBox; 222 | comboboxOpt->rect = option.rect; 223 | comboboxOpt->state = option.state; 224 | comboboxOpt->state |= QStyle::State_Enabled; 225 | comboboxOpt->editable = false; 226 | comboboxOpt->currentText = "text"; 227 | // comboboxOpt->rect = ComboBoxRect(option); 228 | QApplication::style()->drawComplexControl(QStyle::CC_ComboBox, comboboxOpt, painter); 229 | } 230 | else if(index.column() == CONTENT) 231 | { 232 | // 偶数行绘制背景 233 | if( index.row()%2 == 0) 234 | painter->fillRect(opt.rect, QBrush(QColor(52, 113, 34))); 235 | 236 | pen.setColor(QColor(140,200,125)); 237 | } 238 | 239 | if( index.column() != CHECKED ) 240 | { 241 | painter->setPen(Qt::NoPen); 242 | painter->setRenderHint(QPainter::Antialiasing, true); 243 | // 选中时的背景颜色,貌似这里没起作用? 244 | if( opt.state & QStyle::State_Selected ) 245 | { 246 | painter->setBrush(option.palette.highlightedText()); 247 | painter->fillRect(opt.rect, QBrush(QColor(22, 183, 134))); 248 | // QItemDelegate::paint(painter, option, index); 249 | } 250 | // 开始绘制背景颜色和文本 251 | painter->setPen(pen); 252 | drawBackground(painter, opt, index); 253 | painter->drawText(opt.rect, opt.displayAlignment, text); 254 | painter->restore(); 255 | } 256 | } 257 | 258 | bool editorEvent(QEvent *event, QAbstractItemModel *model, 259 | const QStyleOptionViewItem &option, 260 | const QModelIndex &index) 261 | { 262 | if( index.column() != CHECKED ) 263 | return false; 264 | 265 | if( (event->type() == QEvent::MouseButtonRelease) || 266 | (event->type() == QEvent::MouseButtonDblClick) ) 267 | { 268 | QMouseEvent *mouse_event = static_cast(event); 269 | if( mouse_event->button() == Qt::LeftButton && 270 | CheckBoxRect(option).contains(mouse_event->pos()) ) 271 | { 272 | int checked = model->data(index, Qt::DisplayRole).toInt(); 273 | return model->setData(index, checked == 1 ? 0 : 1, Qt::CheckStateRole); 274 | } 275 | } 276 | 277 | return false; 278 | } 279 | 280 | QRect CheckBoxRect(const QStyleOptionViewItemV4 &viewItemStyleOptions)const 281 | { 282 | //绘制按钮所需要的参数 283 | QStyleOptionButton checkBoxStyleOption; 284 | //按照给定的风格参数 返回元素子区域 285 | QRect checkBoxRect = QApplication::style()->subElementRect( QStyle::SE_CheckBoxIndicator, &checkBoxStyleOption); 286 | //返回QCheckBox坐标 287 | QPoint checkBoxPoint(viewItemStyleOptions.rect.x() + viewItemStyleOptions.rect.width() / 2 - checkBoxRect.width() / 2, 288 | viewItemStyleOptions.rect.y() + viewItemStyleOptions.rect.height() / 2 - checkBoxRect.height() / 2); 289 | //返回QCheckBox几何形状 290 | return QRect(checkBoxPoint, checkBoxRect.size()); 291 | } 292 | 293 | QRect ComboBoxRect(const QStyleOptionViewItemV4 &viewItemStyleOptions)const 294 | { 295 | //绘制按钮所需要的参数 296 | QStyleOptionComplex comboBoxStyleOption; 297 | //按照给定的风格参数 返回元素子区域 298 | QRect comboBoxRect = QApplication::style()->subControlRect(QStyle::CC_ComboBox, &comboBoxStyleOption, QStyle::SC_ComboBoxEditField); 299 | //返回QCheckBox坐标 300 | QPoint comboBoxPoint(viewItemStyleOptions.rect.x() + viewItemStyleOptions.rect.width() + comboBoxRect.width() , 301 | viewItemStyleOptions.rect.y() + viewItemStyleOptions.rect.height() / 2 - comboBoxRect.height() / 2); 302 | //返回QCheckBox几何形状 303 | return QRect(comboBoxPoint, comboBoxRect.size()); 304 | } 305 | }; 306 | 307 | #endif // TABLEVIEWPAGE_H 308 | -------------------------------------------------------------------------------- /TableViewPaging.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2013-10-29T10:22:04 4 | # 5 | #------------------------------------------------- 6 | 7 | QT += core gui sql 8 | 9 | greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 10 | 11 | TARGET = TableViewPaging 12 | TEMPLATE = app 13 | 14 | 15 | SOURCES += main.cpp\ 16 | MainWindow.cpp \ 17 | DatabaseManager.cpp \ 18 | TableViewPage.cpp \ 19 | InsertDialog.cpp 20 | 21 | HEADERS += MainWindow.h \ 22 | DatabaseManager.h \ 23 | GlobalConstances.h \ 24 | TableViewPage.h \ 25 | InsertDialog.h 26 | 27 | FORMS += MainWindow.ui \ 28 | InsertDialog.ui 29 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | ** Copyright (C) 2013 Southgis Co.,Ltd. Written by Young Yori, All rights reserved. 3 | **-------------------------------------------------------------------------------- 4 | ** Filename:LinearList.h 5 | ** Author: Young Yori 6 | ** Data: Administrator 2013/12/25 2013 7 | ** Description: 8 | ** This file is part of the Data Development Department Project and shall 9 | ** only be used, modified, and distributed under the terms of the Data 10 | ** Development Department this Source. 11 | ** 12 | ** Included in the build system of the FreeType library. 13 | **-------------------------------------------------------------------------------- 14 | ** www.newdebug.com, 12319597@qq.com 15 | **************************************************************************/ 16 | 17 | #include "MainWindow.h" 18 | #include 19 | #include 20 | 21 | int main(int argc, char *argv[]) 22 | { 23 | QApplication a(argc, argv); 24 | 25 | QTextCodec *codec = QTextCodec::codecForName("GB18030"); 26 | QTextCodec::setCodecForLocale(codec); 27 | QTextCodec::setCodecForCStrings(codec); 28 | QTextCodec::setCodecForTr(codec); 29 | 30 | MainWindow w; 31 | w.setWindowTitle(QObject::tr("TableView Paging")); 32 | w.show(); 33 | 34 | return a.exec(); 35 | } 36 | -------------------------------------------------------------------------------- /screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yuriyoung/TableViewPaging/6cd9e1efbe26f48221c9ac9d09b2bb88e3c0b2e1/screenshot.jpg --------------------------------------------------------------------------------