我有一个gauge.qml,如下所示
Gauge.qml
Item {
property real gaugevalue //this determine the gaugevalue.
width: 100
height: 100
Rectangle {
Image {
x: 0
y: 0
source: "qrc:/gaugebg.png"
}
Image {
x: 50
y: 49
source: "qrc:/needle.png";
rotation: 0
// I am doing some rotation logic with gaugevalue. please ignore logic for now
transform: Rotation {
origin.x: 10; origin.y:10;
angle: gaugevalue
}
}
}
}
另外,我有一个main.qml,如下所示,我放置了我的仪表
main.qml
Window {
id: main
width: 640
height: 480
//gauge position
property int gaugeX: 50
property int gaugeY: 60
Gauge {
id : id_gauge
gaugevalue : 50 //Now I am setting the gaugevalue from here. I need this to be controlled from my GaugeController class.
x:gaugeX
y:gaugeY
}
}
我想要实现的是让我的代码适合MVC架构。我打算用C ++编写一个'GaugeController'类,它将设置'gaugevalue'(后面会有更多的属性)。通过阅读许多导致以不同方式思考的文章我真的很困惑(我看到许多解决方案,比如使用Q_PROPERTY或setProperty等等。(请参阅此链接:https://www.zhieng.com/exposing-qml-object-pointer-to-cc/)。所以如果你能纠正我的代码会很棒在MVC架构中实现这一点。
答案 0 :(得分:0)
使用qmlRegisterType<>()
,然后在QML文件中创建一个GuageController实例,可以通过信号/插槽传递值来控制Guage
的main.cpp
qmlRegisterType<GaugeController>("myApp", 1, 0, "GaugeController");
main.qml
import myApp 1.0
...
GaugeController {
id: id_controller
// heres how you implment a method as a SLOT via QML
onGaugeValueChanged(gaugeValue): {
id_gauge.gaugeValue = id_controller.gaugeValue
}
}
gaugeController.cpp
class GaugeController : public QQuickItem
{
Q_OBJECT
// Q_PROPERTY MACRO allows the property to be read by QML
Q_PROPERTY(int gaugeValue READ gaugeValue WRITE setGaugeValue NOTIFY gaugeValueChanged)
public:
int gaugeValue() { return _gaugeValue; };
signals:
void gaugeValueChanged();
public slots:
void setGaugeValue(newVal) { _gaugeValue = newVal; }
private:
int _gaugeValue;
**编辑**
从main.qml将参数传递给GuageController
GaugeController {
id: controller
gaugeValue: 10
}
// or
function myfunction { controller.gaugeValue = 5 }