【发布时间】:2020-02-18 08:21:22
【问题描述】:
我正在尝试从c++ 上的QML 一侧读取int value,但该值仍然是0 并且不会在c++ 一侧更新,而console.log() 清楚地告诉我它在之后递增每次点击。我在这里做错了什么?
.qml 文件
FocusScope {
property alias myrecordint: startbutton.recordint
Rectangle {
id: buttonPaneShadow
width: bottomColumn.width + 16
height: parent.height
anchors.top: parent.top
anchors.right: parent.right
color: "white"
Column {
anchors {
right: parent.right
top: parent.top
margins: 8
}
id: buttonsColumn
anchors.rightMargin: 20
anchors.topMargin: 20
spacing: 12
CameraButton {
id: startbutton
property int recordint:0
text: "Record"
visible: camera.videoRecorder.recorderStatus == CameraRecorder.LoadedStatus
onClicked:
{
recordint=recordint+1
camera.videoRecorder.record()
console.log(recordint)
}
}
}
}
}
.cpp 文件
QQmlEngine engine;
QQmlComponent component(&engine, QUrl("qrc:/VideoCaptureControls.qml"));
QObject *object = component.create();
qDebug() << "Property value:" << QQmlProperty::read(object, "myrecordint").toInt();
【问题讨论】:
-
将 c++ 暴露给 qml 是一种非常糟糕的方式,反之亦然。 Qt 已经提供了一种将您的 c++ 类与 qml 对象连接起来的方法,请在开发应用程序之前阅读此处doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html。
-
@arnes 非常感谢你,我一定会通过那个链接!我在 QML 方面没有太多经验,但这有帮助!
-
不客气,如果你卡在某个地方,你可以看看例子doc.qt.io/qt-5/qmlextendingexamples.html
-
doc.qt.io/qt-5/qtqml-referenceexamples-adding-example.html 实际上这个例子展示了如何做到这一点。声明和定义 Person 类。在 main.cpp 之后,在调用
engine.load( "your_qml.qml" )之前,添加这段代码,qmlRegisterType<Person>( "your_module_name" , 1 /*major version of your module*/ , 2 /*minor version of your module*/ , "Person" /*Qml type name*/ );,这样它就告诉 qml 引擎将Person类暴露给qml端。您可以访问您的属性,也可以从 qml 端调用public slots:函数 -
@arnes 好的!非常感谢!我会玩,看看我能不能成功!