簡體   English   中英

公開QList <customobj *> 到QML

[英]Exposing QList<customobj *> to QML

我試圖將帶有自定義對象( Sample )的QList暴露給QML。 每當我將這些自定義對象(它們從QObject繼承)存儲到QList<QObject *> ,它們會顯示但沒有信息,但是當我嘗試將它們公開為QList<Sample *> ,它們不會。

sample.h

class Sample : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString getVar READ getVar WRITE setVar NOTIFY varChanged)
public:
    explicit Sample();

    //! Returns var
    QString getVar() const { return var; }

    //! Sets var
    void setVar(const QString &a);

signals:
    varChanged();

protected:
    QString var;
};

包含列表的類看起來像這樣

samplecontrol.h

class SampleManager : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QList<Sample *> getSampleList READ getSampleList NOTIFY sampleListChanged)
public:
    SampleManager(const QString &path);

    //! Returns sample list
    QList<Sample *> getSampleList() const { return sampleList_; }

signals:
    sampleListChanged();

protected:
    QList<Sample *> sampleList_;
};

我正在設置上下文

view_->rootContext()->setContextProperty("slabGridModel", QVariant::fromValue(samplecontrol.getSampleList()));

正如我所說,當我累了

QList<QObject *> datalist;
datalist.append(sampleManager.getSampleList().first());
datalist.append(sampleManager.getSampleList().last());

有效。 如何使用QList<Sample *>

謝謝你的幫助!

您可以傳遞QObjects列表,但問題是如果要添加更多元素,它將不會通知視圖,如果您希望通知視圖,則必須使用繼承自QAbstractItemModel的模型。 另一方面,你如何像qproperty一樣做數據模型,最好公開SampleManager:

samplemodel.h

#ifndef SAMPLEMODEL_H
#define SAMPLEMODEL_H

#include "sample.h"

#include <QAbstractListModel>

class SampleModel : public QAbstractListModel
{
    Q_OBJECT
public:
    using QAbstractListModel::QAbstractListModel;
    ~SampleModel(){
        qDeleteAll(mSamples);
        mSamples.clear();
    }
    int rowCount(const QModelIndex &parent = QModelIndex()) const override{
        if (parent.isValid())
            return 0;
        return mSamples.size();
    }

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override{
        if (!index.isValid())
            return QVariant();
        if(role == Qt::UserRole){
            Sample *sample =  mSamples[index.row()];
            return QVariant::fromValue(sample);
        }
        return QVariant();
    }

    void appendSample(Sample * sample)
    {
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        mSamples << sample;
        endInsertRows();
    }

    QHash<int, QByteArray> roleNames() const{
        QHash<int, QByteArray> roles;
        roles[Qt::UserRole] = "sample";
        return roles;
    }

private:
    QList<Sample *> mSamples;
};


#endif // SAMPLEMODEL_H

samplemanager.h

#ifndef SAMPLEMANAGER_H
#define SAMPLEMANAGER_H

#include "samplemodel.h"

#include <QObject>

class SampleManager : public QObject
{
    Q_OBJECT
    Q_PROPERTY(SampleModel* model READ model WRITE setModel NOTIFY modelChanged)
public:
    using QObject::QObject;
    SampleModel *model() const{
        return mModel.get();
    }
    void setModel(SampleModel *model){
        if(mModel.get() == model)
            return;
        mModel.reset(model);
    }
signals:
    void modelChanged();
private:
    QScopedPointer<SampleModel> mModel;
};

#endif // SAMPLEMANAGER_H

main.cpp中

#include "samplemanager.h"
#include "samplemodel.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QTime>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    SampleManager manager;
    manager.setModel(new SampleModel);

    // test
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&manager](){
        manager.model()->appendSample(new Sample(QTime::currentTime().toString()));
    });
    timer.start(1000);

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("manager", &manager);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    GridView {
        anchors.fill: parent
        model: manager.model
        delegate:
            Rectangle {
            width: 100
            height: 100
            color: "darkgray"
            Text {
                text: sample.getVar
                anchors.centerIn: parent
            }
        }
    }
}

在此輸入圖像描述

完整的示例可以在以下鏈接中找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM