0

我在 QML 中声明了 Rectangle,如下所示:

Rectangle {
        objectName: "myquickitemobject"
        signal doSomething
        MouseArea {
            anchors.fill: parent
            onClicked: { 
                doSomething() 
            }
        }
    }

我可以将 QQuickItem 对象myquickitemobject放入 C++ 中,如下所示

// main.cpp
QQuickItem *my_quickitem = m_qml_item_root->findChild<QQuickItem*>("myquickitemobject");

问题:
如何将signal doSomethingQML 中的 decalred 连接到 C++ 中的函数或 lambda?
试图做类似下面的事情是行不通的..

QObject::connect(my_quickitem, doSomething, []{
    std::cout << "Signal doSomething called" << std::endl;
});
4

1 回答 1

1

在您的班级中声明如下所示的插槽:

Q_SLOT void DoSomething() {
    std::cout << "Do something" << std::endl;
}

然后像下面这样连接它们:

QQuickItem *my_quickitem = m_qml_item_root->findChild<QQuickItem*>("myquickitemobject");
QObject::connect(my_quickitem, SIGNAL(doSomething()), this, SLOT(DoSomething()));
于 2021-03-27T17:31:15.417 回答