我想用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
。
感谢您的每一个回复。