我想單擊按鈕時更改矩形的顏色。它們都在main.qml文件中。我想向C++後端發送一個信號來改變矩形的顏色。我似乎無法從文檔中提供的代碼搞清楚將信號QML連接到C++(Qt5)
main.qml: 進口QtQuick 2.4 進口QtQuick.Controls 1.3 進口QtQuick.Window 2.2 進口QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
id:root
signal mysignal()
Rectangle{
anchors.left: parent.left
anchors.top: parent.top
height : 100
width : 100
}
Button
{
id: mybutton
anchors.right:parent.right
anchors.top:parent.top
height: 30
width: 50
onClicked:root.mysignal()
}
}
main.cpp中:
#include <QApplication>
#include <QQmlApplicationEngine>
#include<QtDebug>
#include <QQuickView>
class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot() {
qDebug() << "Called the C++ slot with message:";
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyClass myClass;
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QPushButton *mybutton = engine.findChild("mybutton");
engine.connect(mybutton, SIGNAL(mySignal()),
&myClass, SLOT(cppSlot()));
return app.exec();
}
任何幫助,將不勝感激!
'QList對象= engine.rootObjects();' 'QPushButton *爲myButton =' 'Object.first() - > findChild( 「myButton的」);' 此代碼仍然給我一個錯誤消息:「沒有匹配函數調用「 我已經將objectName屬性添加到按鈕。 –
user3927312