如何从c++中设置ListView模型

How to set ListView model from C++?

本文关键字:设置 ListView 模型 c++      更新时间:2023-10-16

我想用c++创建ListView选项卡。添加选项卡的一部分是这样做的:D我想每个ListView有一个模型,并能够从c++方面控制模型。到目前为止,我已经这样做了:

c++部分:

SmsModel *model = new SmsModel();
model->createDummyData(phoneNumber);
QObject* tab = findTab(phoneNumber);
if (tab == nullptr)
{
  QObject* pRoot = mAppEngine->rootObjects()[0];
  QObject* m_pTabView= pRoot->findChildren<QObject*>("conversationTabView").first();
  if (m_pTabView)
  {
  QVariant returnedValue;
  QVariant title = phoneNumber;
  QQmlContext *context = new QQmlContext(mAppEngine, mAppEngine);
  context->setContextProperty(QString("myModel"), model);
  QQmlComponent *component = new QQmlComponent(mAppEngine, QUrl("qrc:/ChatView.qml"), this);
  QObject *object = component->create(context);
  QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
  QObject *p = object->findChild<QObject*>("chatView");
  p->setProperty("model", context->contextProperty("myModel"));
  qDebug() << p->property("model");
  object->setProperty("active", QVariant(true));
  component->setParent(m_pTabView);
  QMetaObject::invokeMethod(m_pTabView, "addTab",
  Q_RETURN_ARG(QVariant, returnedValue),
  Q_ARG(QVariant, title),
  Q_ARG(QVariant, QVariant::fromValue(component)));
  object->setProperty("anchors.fill", "parent");
  }

QML部分:

import QtQuick 2.5
import QtQml.Models 2.2
import QtQuick.Window 2.2
import org.example 1.0
Rectangle {
    color: "#E0E0E0"
    ListView {
        objectName: "chatView"
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        clip: true
        model: myModel
        delegate: bubbleDelegate
        Component {
            id: bubbleDelegate
            Rectangle {
                implicitWidth: messageText.implicitWidth + 2*messageText.anchors.margins
                implicitHeight: messageText.implicitHeight + 2*messageText.anchors.margins
                anchors.left: model.received ? parent.left : undefined
                anchors.right: model.received ? undefined : parent.right
                anchors.margins: 5
                id: bubble
                smooth: true
                radius: 10
                color: model.received ? "#673AB7" : "#E040FB"
                Text {
                    id: messageText
                    anchors.fill: parent
                    anchors.margins: 5
                    text: model.message
                    wrapMode: Text.WordWrap;
                    horizontalAlignment: model.received ? Text.AlignLeft : Text.AlignRight
                    color: "white"
                }
            }
        }
    }
}

当我运行我的应用程序时,GUI中没有数据,我有以下错误ReferenceError: myModel is not defined .

感谢大家的回复。

为了使用c++对象作为列表模型,你必须有一个继承自QAbstractListModel的类。请看下面的例子: