我似乎完全迷失在QML中的表单声明中。我有一个正确设置Q_PROPERTies的C ++对象,我可以访问QML中该类的对象,我想在QML中使用滑块。我究竟如何使Slider的值更新对象中属性的信息,反之亦然?
答案 0 :(得分:3)
如果它像常规QML一样,那么以下方法将起作用。
使用明确的Binding或使用Slider的valueChanged信号:
#include <QGuiApplication>
#include <QtQml>
class Object : public QObject
{
Q_OBJECT
Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY valueChanged)
public:
explicit Object(QObject *parent = 0) :
QObject(parent),
mValue(0)
{
}
qreal value() const {
return mValue;
}
void setValue(qreal value) {
if (value != mValue) {
mValue = value;
emit valueChanged();
}
}
signals:
qreal valueChanged();
private:
qreal mValue;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Object object;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("object", &object);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
#include "main.moc"
<强> main.qml:强>
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
width: 400
height: 400
visible: true
Binding {
target: object
property: "value"
value: slider.value
}
Slider {
id: slider
// You can also react to the valueChanged signal of Slider:
//onValueChanged: object.value = value
}
}
使用简单的绑定:
#include <QGuiApplication>
#include <QtQml>
class Object : public QObject
{
Q_OBJECT
Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY valueChanged)
public:
explicit Object(QObject *parent = 0) :
QObject(parent),
mValue(0)
{
}
qreal value() const {
return mValue;
}
void setValue(qreal value) {
if (value != mValue) {
mValue = value;
emit valueChanged();
}
}
signals:
qreal valueChanged();
private:
qreal mValue;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<Object>("Test", 1, 0, "Object");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
#include "main.moc"
<强> main.qml:强>
import QtQuick 2.3
import QtQuick.Controls 1.2
import Test 1.0
ApplicationWindow {
width: 400
height: 400
visible: true
Object {
id: object
value: slider.value
onValueChanged: print(value)
}
Slider {
id: slider
}
}