gpt4 book ai didi

c++ - 如何从 C++ 设置 ListView 模型?

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:04 29 4
gpt4 key购买 nike

我想用 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

感谢您的每一个回复。

最佳答案

为了将 C++ 对象用作列表模型,您必须拥有一个继承自 QAbstractListModel 的类。看一下例子 here .

关于c++ - 如何从 C++ 设置 ListView 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31857205/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com