如何将QML信号与C ++插槽连接? [英] How to connect a QML signal with a C++ slot?
问题描述
我在QML中的 MessageDialog
信号有问题.在我的 MessageDialog
中,有两个按钮分别表示是和否.我想用信号连接每个按钮.这是我的qml文件:
I have a problem with a MessageDialog
signal in QML. In my MessageDialog
I have two buttons for Yes and No. I want to connect each button with a signal.
Here is my qml file:
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")
}
}
这是我的广告位:
class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot(const QString &msg) {
qDebug() << "Called the C++ slot with message:" << msg;
}
};
这就是我在main中使用它的方式:
And here is how i use this in 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();
它给了我错误:
C2665:'QObject :: connect':3个重载都不能转换所有参数类型
C2665: 'QObject::connect': none of the 3 overloads could convert all the argument types
我已经尝试了很多次,但是我无法使QML信号和C ++插槽正常工作.我也尝试从这里 Qt doc 给出示例同样的错误.
I have try many times but I can't make work QML signal and C++ slots. Also I have try the example from here Qt doc and give me the same error.
有人可以告诉我如何为 MessageDialog
连接QML信号和C ++插槽吗?
Can somebody give me an idea how to connect QML signal and C++ slots for a MessageDialog
?
推荐答案
您的QML文件是:
Item{
MessageDialog {
signal qmlYesSig(string msg)
signal qmlNoSig (string msg)
[...]
}
}
您的C ++代码为:
QObject *item = view.rootObject();
AddData myClass;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
这意味着您正在QML文件的根项目中寻找一个名为"qmlSignal"的信号.这个根项目就是
It means that you are looking for a signal called "qmlSignal" in the root item of your QML file. This root item is simply
Item{}
如您所见,没有称为"qmlSignal"的信号.
As you can see, there is no signal called "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")
}
}
这篇关于如何将QML信号与C ++插槽连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!