[英]How to connect a QML signal with a C++ slot?
I have a problem with a MessageDialog
signal in QML. 我在QML中遇到MessageDialog
信号问题。 In my MessageDialog
I have two buttons for Yes and No . 在我的MessageDialog
我有两个按钮,分别是和否 。 I want to connect each button with a signal. 我想用信号连接每个按钮。 Here is my qml file: 这是我的qml文件:
import QtQuick 2.2
import QtQuick.Dialogs 1.1
Item{
MessageDialog {
signal qmlYesSig(string msg)
signal qmlNoSig (string msg)
title: "Send data?"
icon: StandardIcon.Question
text: "Do you want to save your data on the online platform?"
detailedText: "Click Yes "
standardButtons: StandardButton.Yes | StandardButton.No
Component.onCompleted: visible = true
onYes: qmlYesSig("From yes")
onNo: qmlNoSig("From no")
}
}
Here is my slot: 这是我的插槽:
class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot(const QString &msg) {
qDebug() << "Called the C++ slot with message:" << msg;
}
};
And here is how i use this in main: 以下是我在main中如何使用它:
QQuickView view(QUrl::fromLocalFile("window.qml"));
QObject *item = view.rootObject();
AddData myClass;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
view.show();
It give me the error: 它给了我错误:
C2665: 'QObject::connect': none of the 3 overloads could convert all the argument types C2665:'QObject :: connect':3个重载中没有一个可以转换所有参数类型
I have try many times but I can't make work QML signal and C++ slots. 我已经尝试了很多次,但我无法工作QML信号和C ++插槽。 Also I have try the example from here Qt doc and give me the same error. 另外我从这里尝试Qt doc的例子并给我同样的错误。
Can somebody give me an idea how to connect QML signal and C++ slots for a MessageDialog
? 有人可以给我一个关于如何为MessageDialog
连接QML信号和C ++插槽的想法吗?
You can expose C++ QObject to QML engine and connecting to the slots of C++ QObject from QML side : 您可以将C ++ QObject公开给QML引擎并从QML端连接到C ++ QObject的插槽:
In C++ file : 在C ++文件中:
view.rootContext()->setContextProperty("object", this); // replace this with appropriate object
In Qml : 在Qml中:
qmlYesSig.connect(object.cppSlot);
Your QML file is: 您的QML文件是:
Item{
MessageDialog {
signal qmlYesSig(string msg)
signal qmlNoSig (string msg)
[...]
}
}
And your C++ code is: 你的C ++代码是:
QObject *item = view.rootObject();
AddData myClass;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
It means that you are looking for a signal called "qmlSignal" in the root item of your QML file. 这意味着您正在QML文件的根项中查找名为“qmlSignal”的信号。 This root item is simply 这个根项很简单
Item{}
As you can see, there is no signal called "qmlSignal". 如您所见,没有称为“qmlSignal”的信号。
You have to define the signal in the root item and emit it from the message box. 您必须在根项目中定义信号并从消息框中发出它。
Item{
signal qmlSignal(string msg)
MessageDialog {
onYes: parent.qmlSignal("From yes")
onNo: parent.qmlSignal("From no")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.