我想单击按钮时更改矩形的颜色。它们都在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