C++数据模型应用在QML委托代理机制中
之前文章中介绍过在Qt-Widget和QML中如何使用委托代理机制(Model-View-Delegate),对应的文章链接分别如下所示:
QT中Model-View-Delegate委托代理机制
QML基础
在开发的过程中发现在QML中直接定义操作数据模型比较繁琐费力,不如C++的数据模型好用。这里就介绍一下如何在QML中调用C++定义的数据模型,实现数据模型的混合使用。
定义数据模型
定义的C++数据模型和Qt-Widget中定义的数据模型相同。模型主要用来存储本地图片的ID的对应的图片地址。
实现如下:
//picturemodel.h
#ifndef PICTUREMODEL_H
#define PICTUREMODEL_H
#include <memory>
#include <vector>
#include <QAbstractListModel>
#include <QUrl>
class Picture
{
public:
Picture(const QString & filePath = "")
{
mPictureUrl = QUrl::fromLocalFile(filePath);
}
Picture(const QUrl& fileUrl)
{
mPictureUrl = fileUrl;
}
int pictureId() const
{
return mPictureId;
}
void setPictureId(int pictureId)
{
mPictureId = pictureId;
}
QUrl pictureUrl() const
{
return mPictureUrl;
}
void setPictureUrl(const QUrl &pictureUrl)
{
mPictureUrl = pictureUrl;
}
private:
int mPictureId; // 图片ID
QUrl mPictureUrl; //图片的地址
};
class PictureModel : public QAbstractListModel
{
Q_OBJECT
public:
//自定义每个元素的数据类型
enum Roles {
UrlRole = Qt::UserRole + 1,
FilePathRole
};
PictureModel(QObject* parent = 0);
//向数据模型中添加单个数据
QModelIndex addPicture(const Picture& picture);
Q_INVOKABLE void addPictureFromUrl(const QUrl& fileUrl);
//模型的行数
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
//获取某个元素的数据
QVariant data(const QModelIndex& index, int role) const override;
//删除某几行数据
Q_INVOKABLE bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override;
//每个元素类别的名称
QHash<int, QByteArray> roleNames() const override;
//加载用户图片
Q_INVOKABLE void loadPictures();
//清空模型的中的数据,但不移除本地文件数据
void clearPictures();
public slots:
//清空模型,删除本地文件中的数据
void deleteAllPictures();
private:
void resetPictures();
bool isIndexValid(const QModelIndex& index) const;
private:
std::unique_ptr<std::vector<std::unique_ptr<Picture>>> mPictures;
};
#endif // PICTUREMODEL_H
//picturemodel.cpp
#include "picturemodel.h"
#include <QUrl>
using namespace std;
PictureModel::PictureModel(QObject* parent) :
QAbstractListModel(parent),
mPictures(new vector<unique_ptr<Picture>>())
{
}
QModelIndex PictureModel::addPicture(const Picture& picture)
{
int rows = rowCount();
beginInsertRows(QModelIndex(), rows, rows);
unique_ptr<Picture>newPicture(new Picture(picture));
mPictures->push_back(move(newPicture));
endInsertRows();
return index(rows, 0);
}
void PictureModel::addPictureFromUrl(const QUrl& fileUrl)
{
addPicture(Picture(fileUrl));
}
int PictureModel::rowCount(const QModelIndex& ) const
{
return mPictures->size();
}
QVariant PictureModel::data(const QModelIndex& index, int role) const
{
if (!isIndexValid(index))
{
return QVariant();
}
const Picture& picture = *mPictures->at(index.row());
switch (role) {
//展示数据为图片的名称
case Qt::DisplayRole:
return picture.pictureUrl().fileName();
break;
//图片的URL
case Roles::UrlRole:
return picture.pictureUrl();
break;
//图片地址
case Roles::FilePathRole:
return picture.pictureUrl().toLocalFile();
break;
default:
return QVariant();
}
}
bool PictureModel::removeRows(int row, int count, const QModelIndex& parent)
{
if (row < 0
|| row >= rowCount()
|| count < 0
|| (row + count) > rowCount()) {
return false;
}
beginRemoveRows(parent, row, row + count - 1);
int countLeft = count;
while(countLeft--) {
const Picture& picture = *mPictures->at(row + countLeft);
}
mPictures->erase(mPictures->begin() + row,
mPictures->begin() + row + count);
endRemoveRows();
return true;
}
QHash<int, QByteArray> PictureModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "name";
roles[Roles::FilePathRole] = "filepath";
roles[Roles::UrlRole] = "url";
return roles;
}
void PictureModel::loadPictures()
{
beginResetModel();
endResetModel();
}
void PictureModel::clearPictures()
{
resetPictures();
}
void PictureModel::resetPictures()
{
beginResetModel();
mPictures.reset(new vector<unique_ptr<Picture>>());
endResetModel();
return;
}
void PictureModel::deleteAllPictures()
{
resetPictures();
}
bool PictureModel::isIndexValid(const QModelIndex& index) const
{
if (index.row() < 0
|| index.row() >= rowCount()
|| !index.isValid()) {
return false;
}
return true;
}
定义C++数据模型的时候有几点需要注意:
1.如果想在QML中访问模型的某个方法的话需要在方法声明的时候添加Q_INVOKABLE宏
Q_INVOKABLE void addPictureFromUrl(const QUrl& fileUrl);
2.在QML中通过每个元素类别的名称来进行访问,对应的类别名称的定义如下:
QHash<int, QByteArray> PictureModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "name";
roles[Roles::FilePathRole] = "filepath";
roles[Roles::UrlRole] = "url";
return roles;
}
定义图片缓存器
由于数据模型中包含图片数据,为了便于在QML中访问图片资源,添加图片缓存器。缓存器继承自QQuickImageProvider。对应的实现如下所示:
//PictureImageProvider.h
#ifndef PICTUREIMAGEPROVIDER_H
#define PICTUREIMAGEPROVIDER_H
#include <QQuickImageProvider>
#include <QCache>
class PictureModel;
class PictureImageProvider : public QQuickImageProvider
{
public:
static const QSize THUMBNaiL_SIZE;
PictureImageProvider(PictureModel* pictureModel);
//请求图片
QPixmap requestPixmap(const QString& id, QSize* size, const QSize& requestedSize) override;
//获取缓存
QPixmap* pictureFromCache(const QString& filepath, const QString& pictureSize);
private:
//数据模型
PictureModel* mPictureModel;
//图片缓存容器
QCache<QString, QPixmap> mPicturesCache;
};
#endif // PICTUREIMAGEPROVIDER_H
//PictureImageProvider.cpp
#include "PictureImageProvider.h"
#include "PictureModel.h"
//全屏显示
const QString PICTURE_SIZE_FULL = "full";
//缩略显示
const QString PICTURE_SIZE_THUMBNAIL = "thumbnail";
//缩略显示的尺寸
const QSize PictureImageProvider::THUMBNAIL_SIZE = QSize(350, 350);
PictureImageProvider::PictureImageProvider(PictureModel* pictureModel) :
QQuickImageProvider(QQuickImageProvider::Pixmap),
mPictureModel(pictureModel),
mPicturesCache()
{
}
QPixmap PictureImageProvider::requestPixmap(const QString& id, QSize* , const QSize& )
{
QStringList query = id.split('/');
if (!mPictureModel || query.size() < 2) {
return QPixmap();
}
//第几个图片数据
int rowId = query[0].toInt();
//显示模式是缩略显示还是全屏显示
QString pictureSize = query[1];
QUrl fileUrl = mPictureModel->data(mPictureModel->index(rowId, 0), PictureModel::Roles::UrlRole).toUrl();
return *pictureFromCache(fileUrl.toLocalFile(), pictureSize);
}
QPixmap* PictureImageProvider::pictureFromCache(const QString& filepath, const QString& pictureSize)
{
QString key = QStringList{ pictureSize, filepath }
.join("-");
//不包含图片的时候创建新的缓存
QPixmap* cachePicture = nullptr;
if (!mPicturesCache.contains(key))
{
QPixmap originalPicture(filepath);
if (pictureSize == PICTURE_SIZE_THUMBNAIL)
{
cachePicture = new QPixmap(originalPicture
.scaled(THUMBNAIL_SIZE,
Qt::KeepAspectRatio,
Qt::SmoothTransfORMation));
}
else if (pictureSize == PICTURE_SIZE_FULL)
{
cachePicture = new QPixmap(originalPicture);
}
mPicturesCache.insert(key, cachePicture);
}
//包含的时候直接访问缓存
else
{
cachePicture = mPicturesCache[key];
}
return cachePicture;
}
初始化QML引擎
在QML引擎初始化的时候添加对应的数据模型和图片缓存器,对应的实现如下:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "picturemodel.h"
#include "PictureImageProvider.h"
int main(int arGC, char *argv[])
{
QGuiApplication app(argc, argv);
PictureModel pictureModel;
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();
//添加数据模型和图片缓存器
context->setContextProperty("pictureModel", &pictureModel);
//图片Provider的ID是"pictures"
engine.addImageProvider("pictures", new PictureImageProvider(&pictureModel));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
QML中访问C++数据模型
在QML中通过数据模型访问数据,通过图片缓存器访问对应的图片资源,对应的实现如下:
//main.qml
import QtQuick 2.8
import QtQuick.Dialogs 1.2
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("QML-mvc")
RowLayout {
id:tool_layout
//添加图片的按钮
ToolButton {
background: Image {
source: "qrc:/image/photo-add.svg"
}
onClicked: {
dialog.open()
}
}
//删除图片的按钮
ToolButton {
background: Image {
source: "qrc:/image/photo-delete.svg"
}
onClicked: {
pictureModel.removeRows(pictureListView.currentIndex,1)
}
}
}
//网格视图
GridView {
id: pictureListView
model: pictureModel
anchors.top:tool_layout.bottom
width: parent.width;
height: parent.height - tool_layout.height
anchors.leftMargin: 10
anchors.rightMargin: 10
cellWidth : 300
cellHeight: 230
//对应的每个元素的代理
delegate: Rectangle {
width: 290
height: 200
color: GridView.isCurrentItem?"#4d9cf8":"#ffffff" //选中颜色设置
Image {
id: thumbnail
anchors.fill: parent
fillMode: Image.PreserveAspectFit
cache: false
//通过缓存器访问图片
//image://pictures/访问器的ID
//index + "/thumbnail" 图片索引和显示模式
source: "image://pictures/" + index + "/thumbnail"
}
//访问图片的名称
Text {
height: 30
anchors.top: thumbnail.bottom
text: name
font.pointSize: 16
anchors.horizontalCenter: parent.horizontalCenter
}
//鼠标点击设置当前索引
MouseArea{
anchors.fill: parent
onClicked: {
pictureListView.currentIndex = index;
}
}
}
}
//图片选择窗口
FileDialog {
id: dialog
title: "Select Pictures"
folder: shortcuts.pictures
onAccepted: {
var pictureUrl = dialog.fileUrl
pictureModel.addPictureFromUrl(pictureUrl)
dialog.close()
}
}
}
显示效果如下图所示:
到此这篇关于C++数据模型应用在QML委托代理机制中的文章就介绍到这了,更多相关C++数据模型内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章