简体   繁体   中英

QML c++ signal & slots

I've got following code:

main.cpp

QDeclarativeView *qmlView = new QDeclarativeView();
qmlView->setSource(QUrl("qrc:/nav.qml"));
ui->nav->addWidget(qmlView);
Blockschaltbild bild;
QObject *value = qmlView->rootObject();
QObject::connect(value, SIGNAL(testSig()), &bild, SLOT(BlockSlot()));

The signals and slots connect correctly. (QObject::connect returns "true")

qml file:

Rectangle {
    id: rectangle1
    ....
    signal testSig()
    MouseArea{
         id: mousearea
         anchors.fill: parent
         onEntered: parent.color = onHoverColor
         onExited:  parent.color = parent.buttonColor
         onClicked: {
                        rectangle1.testSig()
                        console.log("Button clicked")
                    }
    }
}

This is where the slot is located:

Blockschaltbild.h

class Blockschaltbild: public QObject
{
    Q_OBJECT
public slots:
    void BlockSlot(){
        cout << "Slot is working" << endl;
    }
public:
    ....
}

If I click on the mouse area, the console shows "Button clicked" but not "Slot is working". I use Qt 4.8.4 with QtQuick 1.1. Where is my mistake?

If you simply require to work with your Blockschaltbild object in QML, you can also decide against a loose coupling with signal and slots and simply pass your object as a context parameter, to make it available in QML.

QDeclarativeView *qmlView = new QDeclarativeView();
qmlView->setSource(QUrl("qrc:/nav.qml"));
ui->nav->addWidget(qmlView);

Blockschaltbild* bild;
QObject *value = qmlView->engine().rootContext()->setContextProperty("bild", bild);

You can then call the BlockSlot() slot of your object from QML with:

Rectangle {
    id: rectangle1
    ....

    MouseArea{
       id: mousearea
       anchors.fill: parent
       onEntered: parent.color = onHoverColor
       onExited:  parent.color = parent.buttonColor
       onClicked: {
           bild.BlockSlot() // call BlockSlot of "bild" context property
           console.log("Button clicked")
        }
    }
}

It is also possible to use qmlRegisterType , which allows you to create instances of your Blockschaltbild class with QML. See here for more information.

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