0
votes

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?

1
Is it a typo that you wrote restSig() instead of testSig()? And does the rectangle have an id: rectangle1?leemes
Yes, it was a typo. I just corrected it. rectangle1 is the id of rectangle. I just forgot to write it in there.shtdown
Try to move BlockSlot definition to the .cpp file, because Qt will generate MOC file and link it with cpp file.Dmitry
Have yout tried that cout << "sth" in some other place and it worked? For me I have to use qDebug() << "sth" insteadNico Rodsevich

1 Answers

0
votes

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.