【自制软件】PDF学习宝-开发日记15--书库页实现二

239 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情


📒博客首页:何名取 的个人主页 - 文章 - 掘金 (juejin.cn)
🎉欢迎关注🔎点赞👍收藏⭐️留言📝
❤️期待一起交流!
🙏作者水平很有限,如果发现错误,求告知,多谢!
🌺有问题可私信交流!!!


书库页实现二

前言

上一篇用一个Demo来研究了到底QSqlTableModel模型与QListView视图能不能关联使用?得出的答案是可以的。本节就在PDF学习宝中使用一下。另外本节将会使用到自定义的代理来显示书库页。

自定义代理

创建自定义代理的类:

image.png

创建完成后,需要重写继承的QItemDelegate类的两个展示函数。其中sizeHint函数是有关QList视图大小的,而paint函数则是重绘函数,可以绘制想要的效果。下面注释掉的一些函数现在暂时用不上,后面可能需要在美化样式时使用到。

#ifndef QCUSTOMDELEGATE_H
#define QCUSTOMDELEGATE_H

#include <QItemDelegate>

class QCustomDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    QCustomDelegate();

     QSize sizeHint(const QStyleOptionViewItem &option,
                    const QModelIndex &index) const override;

      void paint(QPainter *painter, const QStyleOptionViewItem &option,
                 const QModelIndex &index) const override;

//    //自定义代理组件必须继承以下4个函数
//        QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
//                              const QModelIndex &index) const Q_DECL_OVERRIDE;

//        void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
//        void setModelData(QWidget *editor, QAbstractItemModel *model,
//                          const QModelIndex &index) const Q_DECL_OVERRIDE;
//        void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
//                                  const QModelIndex &index) const Q_DECL_OVERRIDE;
};

#endif // QCUSTOMDELEGATE_H

这两个函数的重写:


#include "qcustomdelegate.h"
#include <QPainter>

QCustomDelegate::QCustomDelegate()
{

}

QSize QCustomDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(index);
    return QSize(90, 160);
}

void QCustomDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QRectF rect = option.rect;
    if(option.state & QStyle::State_Selected)
        painter->fillRect(rect,QBrush(QColor("#1296bd")));
    else
        painter->fillRect(rect,QBrush(QColor("#FFFFFF")));
    painter->drawText(rect, Qt::AlignCenter, index.model()->data(index, Qt::EditRole).toString());
}

模型视图代理三合一

定义好代理后就可以将这三者进行结合了。首先将数据库与数据模型进行连接,设置好数据库中对应的表。再进行编辑策略的设置与排序的设置。之后将选择模型设置为当前的数据模型。最后是将视图与数据模型连接并为视图设置好代理。

void Widget::booksView_init()
{
    tabModel = new QSqlTableModel(this,db);
    tabModel->setTable("book");//设置数据表
    tabModel->setEditStrategy(QSqlTableModel::OnManualSubmit);  //OnManualSubmit , OnRowChange
    tabModel->setSort(0,Qt::AscendingOrder);
    theSelection=new QItemSelectionModel(tabModel);


    books_view->setModel(tabModel);
    books_view->setModelColumn(1);
    books_view->setSelectionModel(theSelection);
    books_view->setItemDelegate(customdelegate);
    tabModel->select(); //打开数据表
}

以下是程序运行效果图:

image.png