根据 Qt5 文档:公开包括 qt 插槽在内的方法,所有从 QObject 继承的 C++ 类的公共插槽都可以从 QML 访问这里我做了什么:
C++
class MyClass : public QObject
{
Q_OBJECT
public slots:
void doStuffFromQmlSlot()
{
qDebug() << Q_FUNC_INFO;
}
public:
MyClass()
{
qDebug() << Q_FUNC_INFO;
}
};
Run Code Online (Sandbox Code Playgroud)
我的main.cpp包含:
MyClass myClass;
QQmlEngine engine;
engine.rootContext()->setContextProperty( "myclass", &myClass );
QQmlComponent component( &engine, QUrl::fromLocalFile("qml/qtquick-01/main.qml") );
component.create();
Run Code Online (Sandbox Code Playgroud)
质量管理语言
import QtQuick 2.0
Rectangle {
width: 360
height: 360
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
myclass.doStuffFromQmlSlot(); …Run Code Online (Sandbox Code Playgroud)