在QML中调用C++类的方法,需要先在C++中创建该类的实例,并将其注册为QML类型。然后在QML中,你可以像使用其他QML类型一样使用它。
1、在qml中添加按钮
在qml的title后添加:
Button{
x:100 // 设置按钮的横坐标
y:100 // 设置纵坐标
text:"我是按钮" // 按钮文本
// 信号槽连接
onClicked: {
console.log("我被点击了")
}
}
2、添加类,注册为qml类型
#include <QObject>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = nullptr);
Q_INVOKABLE void myMethod(const QString ¶m) {
// 实现方法
qDebug() << "Method called with parameter:" << param;
}
}
在main.cpp中添加
// 创建C++类实例并注册到QML
MyClass myClass;
qmlRegisterType<MyClass>("com.mycompany", 1, 0, "MyClass");
3、在qml中添加实例、调用类的方法
import com.mycompany 1.0
。。。。。。
MyClass {
id: myClassInstance
}
Button{
// 信号槽连接
onClicked: {
console.log("我被点击了")
// 调用C++类的方法
myClassInstance.myMethod("Hello from QML")
}
}
QT技术交流QQ群:462331087
4456

被折叠的 条评论
为什么被折叠?



