我有一个我称之为 C++“服务”的东西,我想将其接口公开给 QML。我正在尝试使用QQmlContext's setContextProperty将对象链接到 QML 并从QML Connections block.
QML 不会像之前我没有在 QML 上下文中注册服务时那样抱怨引用错误:
qrc:/main.qml:13: ReferenceError: service is not defined
所以,QML 似乎找到了service
现在对象,但是 QML 插槽 javascript 函数没有被调用。我在 Qt Creator 中看到了这一点:
Debugging starts
QML debugging is enabled. Only use this in a safe environment.
QML Debugger: Waiting for connection on port 62301...
Calling the clbk signal
Debugging has finished
应该有一个In onClbk
每条消息console.log("In onClbk");
我知道我可以使用QMetaObject::invokeMethod直接调用 QML 对象的函数,但我试图通过使用信号和槽来实现更宽松的耦合。
我想避免创建QQuickItem
如果可能的话,在 QML 中实例化服务。
不幸的是,样板代码很多,这是我的SSCCE.
这是通过 Qt Creator 5.4 创建的所有项目目录的 zip 文件。
main.cpp
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
auto rc = engine.rootContext();
auto service = new Service();
engine.rootContext()->setContextProperty(QStringLiteral("service"), service);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
// invoke the trigger arbitrarily
QTimer *timer = new QTimer();
timer->setSingleShot(true);
QObject::connect(timer, SIGNAL(timeout()), service, SLOT(trigger_clbk()));
timer->start(4000);
return app.exec();
}
服务.h
class Service : public QQuickItem {
Q_OBJECT
public:
virtual ~Service(){}
signals:
void clbk();
public slots:
void trigger_clbk() {
qDebug()<<"Calling the clbk signal";
clbk();
}
};
main.qml
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
MainForm {
anchors.fill: parent
mouseArea.onClicked: {
Qt.quit();
}
// subscribe to a signal
Connections {
target: service
onClbk: function(){
console.log("In onClbk");
}
}
}
}
Main.ui.qml
import QtQuick 2.3
Rectangle {
property alias mouseArea: mouseArea
width: 360
height: 360
MouseArea {
id: mouseArea
anchors.fill: parent
}
Text {
anchors.centerIn: parent
text: "Hello World"
}
}