当我点击一个按钮时,我想改变矩形的颜色 . 它们都在main.qml文件中 . 我想向C后端发送一个信号来改变矩形的颜色 . 我似乎无法从文档中给出的代码中弄清楚
main.qml:import 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();
}
任何帮助,将不胜感激!
2 回答
首先,
QObject::findChild
通过 object name 找到QObjects,而不是id(无论如何都是上下文的本地) . 因此在QML中你需要这样的东西:其次,我认为你需要在引擎本身上执行
findChild
,而不是从QQmlApplicationEngine::rootObjects()
返回它的根对象 .第三,QML中的
Button
由您只是将结果分配给QPushButton *
的类型表示,但您需要坚持使用通用QObject *
.我必须创建一个单独的类和头文件,然后将它连接到main.cpp中的信号
main.cpp中
myclass.h
myclass.cpp