简体   繁体   中英

How to connect a QML signal with a C++ slot?

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")
    }
}

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:

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

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.

Can somebody give me an idea how to connect QML signal and C++ slots for a MessageDialog ?

You can expose C++ QObject to QML engine and connecting to the slots of C++ QObject from QML side :

In C++ file :

view.rootContext()->setContextProperty("object", this); // replace this with appropriate object

In Qml :

qmlYesSig.connect(object.cppSlot);

Your QML file is:

Item{
    MessageDialog {
        signal qmlYesSig(string msg)
        signal qmlNoSig (string msg)

        [...]
    }
}

And your C++ code is:

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. This root item is simply

Item{}

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")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM