简体   繁体   English

从 C++ 中的 QQuickItem 创建列表视图

[英]Creating listview from QQuickItem in C++

I am trying to make a listview component using QQuickItem and load its model using QAbstractListModel.我正在尝试使用 QQuickItem 制作一个列表视图组件,并使用 QAbstractListModel 加载它的 model。 Below are the steps which i tried.以下是我尝试过的步骤。

listviewComponent.qml listviewComponent.qml

ListView {
   required model

    delegate: Text {
        required property string type
        required property string size

        text: type + ", " + size
        }
}

Model.h Model.h

class Model
{
public:
    Model(const QString& type, const QString& size);

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;
};

class CustomModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum Roles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    CustomModel(QObject* parent = 0);

    void addElement(const Model& pElement);

    int rowCount(const QModelIndex& parent = QModelIndex()) const;

    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Model> m_list;
};

Model.cpp Model.cpp

Model::Model(const QString& type, const QString& size)
    : m_type(type), m_size(size)
{
}

QString Model::type() const
{
    return m_type;
}

QString Model::size() const
{
    return m_size;
}

CustomModel::CustomModel(QObject* parent)
    : QAbstractListModel(parent)
{
}

void CustomModel::addElement(const Model &pElement)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_list << pElement;
    endInsertRows();
}

int CustomModel::rowCount(const QModelIndex& parent) const {
    Q_UNUSED(parent);
    return m_list.count();
}

QVariant CustomModel::data(const QModelIndex& index, int role) const {
    if (index.row() < 0 || index.row() >= m_list.count())
        return QVariant();

    const Model& mod = m_list[index.row()];
    if (role == TypeRole)
        return mod.type();
    else if (role == SizeRole)
        return mod.size();
    return QVariant();
}

QHash<int, QByteArray> CustomModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}

Myclass.h我的班级.h

class myclass : public QObject
{
    Q_OBJECT
public:
    myclass();

    inline int createUI(QQmlApplicationEngine &engine){
        QQuickWindow *window = qobject_cast<QQuickWindow*>(engine.rootObjects().at(0));
        if (!window) {
            qFatal("Error: Your root item has to be a window.");
            return -1;
        }

        QQuickItem *root = window->contentItem();

        window->setWidth(600);
        window->setHeight(500);

        QQmlComponent listviewComp(&engine, QUrl(QStringLiteral("qrc:/listviewComponent.qml")));
       
        CustomModel model;
        model.addElement(Model("Wolf", "Medium"));
        model.addElement(Model("Polar bear", "Large"));
        model.addElement(Model("Quoll", "Small"));

        QQuickItem *listview = qobject_cast<QQuickItem*>(listviewComp.createWithInitialProperties({ {"model", QVariant::fromValue(&model)} }));
        QQmlEngine::setObjectOwnership(listview, QQmlEngine::CppOwnership);
        listview->setParentItem(root);
        listview->setParent(&engine);
        listview->setProperty("objectName", "lv");
        listview->setWidth(200);
        listview->setHeight(100);
        listview->setX(250);
        listview->setY(30);
 
       window->show();

        return 0;
}
};

main.cpp主文件

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    engine.load(url);

    QQmlContext *item = engine.rootContext();
    myclass myClass;
    item->setContextProperty("_myClass", &myClass);

    myClass.createUI(engine);

    return app.exec();
}

Problem : Listview is getting displayed but with only one row, but there are 3 rows added in CustomModel.问题:Listview 正在显示,但只有一行,但在 CustomModel 中添加了 3 行。 I am assuming some problem with createWithInitialProperties, but couldnt able to crack it.我假设 createWithInitialProperties 存在一些问题,但无法破解它。

The problem is caused because "model" is a local variable that will be destroyed as soon as createUI is finished executing, and what you see as the first row is just a cache, you shouldn't actually see a row (it looks like a bug).问题是因为“模型”是一个局部变量,一旦 createUI 执行完毕就会被销毁,而你看到的第一行只是一个缓存,你实际上不应该看到一行(它看起来像漏洞)。 The solution is to use the heap memory:解决方法是使用堆memory:

// ...
CustomModel *model =  new CustomModel(window);
model->addElement(Model("Wolf", "Medium"));
model->addElement(Model("Polar bear", "Large"));
model->addElement(Model("Quoll", "Small"));

QQuickItem *listview = qobject_cast<QQuickItem*>(listviewComp.createWithInitialProperties({ {"model", QVariant::fromValue(model)} }));
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从C ++扩展QQuickItem创建QQuickWindow作为子级? - How to create QQuickWindow as a child from a C++ extended QQuickItem? 如何在C ++中的精确帧处设置QQuickItem位置? - How to set the QQuickItem position at a precise frame from C++? 在C ++中调用QQuickItem(TextArea)的方法 - Invoke methods of QQuickItem (TextArea) in C++ 如何在运行时使用C ++创建虚拟QQuickItem - How to create a dummy QQuickItem in C++ at runtime 如何在C ++方面从头开始创建新的QQuickItem副本,并具有与现有副本相同的属性 - How to create a new QQuickItem copy from scratch on C++ side with the same properties as an existing one 来自C ++的QQuickItem实例化和设置难题(不允许将任何东西传递给构造函数) - QQuickItem instantiation from C++ and setup conundrum (not allowed to pass anything to the constructor) 将QQuickItem指针的子类赋予另一个C ++对象 - Give subclass of QQuickItem pointer to another C++ object C ++ QQuickItem:如何在项目尺寸更改时触发功能 - C++ QQuickItem: How to trigger a function on item size change 如何将X和Y转换后的值应用于C ++端的QQuickItem - How to get the X and Y translated values applied to a QQuickItem on to the C++ side 如何从C ++设置ListView模型? - How to set ListView model from C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM