gpt4 book ai didi

c++ - QQuickWidget与C++交互

转载 作者:可可西里 更新时间:2023-11-01 18:37:46 28 4
gpt4 key购买 nike

我正在体验新的 QQuickWidget。我如何在 QQuickWidget 和 C++ 之间进行交互?

C++

QQuickWidget *view = new QQuickWidget();
view->setSource(QUrl::fromLocalFile("myqml.qml"));
view->setProperty("test", 0);

myLayout->addWidget(view);

QML

import QtQuick 2.1

Rectangle {
id: mainWindow
width: parent.width
height: parent.height

Text {
id: text
width: mainWindow.width
font.pixelSize: 20
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
text: test
}
}

text: test 不起作用:ReferenceError: test is not defined

如何通过 C++ 为我的 QML 文件提供一些属性?

是否也可以在 C++ 中获取 Text 对象并更新其文本?

最佳答案

试一试:

view->rootContext()->setContextProperty("test", "some random text");

代替

view->setProperty("test", 0);

setProperty(name, val)如果对象具有定义为 Q_PROPERTY 的属性 name,则有效。

可以将 QObject 派生对象作为 view 的上下文属性传递:

class Controller : public QObject
{
Q_OBJECT
QString m_test;

public:
explicit Controller(QObject *parent = 0);

Q_PROPERTY(QString test READ test WRITE setTest NOTIFY testChanged)

QDate test() const
{
return m_test;
}

signals:

void testChanged(QString arg);

public slots:

void setTest(QDate arg)
{
if (m_test != arg) {
m_test = arg;
emit testChanged(arg);
}
}
};

Controller c;
view->rootContext()->setContextProperty("controller", &c);

Text {
id: text
width: mainWindow.width
font.pixelSize: 20
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
text: controller.test
}

Is it also possible to get the Text object in C++ and update its text?

一般来说,好像不是best approach -- 如果 c++ 代码遵循模型- View 模式,则它不应该知道表示。

然而,如描述的那样是可能的here .

关于c++ - QQuickWidget与C++交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23912633/

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