[Qt-interest] QML signal connections
Carl Snellman
carl.snellman at gmail.com
Wed Aug 18 08:32:58 CEST 2010
Hey,
I'm trying to use QML with C++ to create the GUI for my application,
but I bumped to a problem I havent' been able to solve after a day of
studying/trying.
I created a button in QML, and I'd like to connect its signal to a C++
class slot so that I get to react to the button press; Just like you
would connect QPushButton. However, I cannot figure out how to make
this connection. I tried to find the child object, but always return
null, so I cannot connect that way. I dont know how I would make the
connection in the QML file side (if it is possible)
I attached minimal app below to demonstrate what I've tried.
Any help is greatly appreciated!
Thanks,
Carl
main.cpp
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#include <QtGui/QApplication>
#include <QtDeclarative>
class MyType : public QObject {
Q_OBJECT
public:
MyType(QObject *parent = 0) : QObject(parent) {}
public slots:
void doSomething() {
qDebug() << "DoSomething!";
}
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
qmlRegisterType<MyType>("MyType", 1,0, "MyType");
QGraphicsView *graphicsView = new QGraphicsView;
graphicsView->setGeometry(QRect(0, 0, 500, 500));
QGraphicsScene* scene = new QGraphicsScene(0, 0, 500, 500);
graphicsView->setScene(scene);
QDeclarativeEngine *engine = new QDeclarativeEngine;
QDeclarativeComponent component(engine, QUrl("qrc:/myqml.qml"));
QDeclarativeItem *root = qobject_cast<QDeclarativeItem
*>(component.create());
scene->addItem(root);
//QObject* rect = root->findChild<QObject*>("button");
QObject* button = qFindChild<QObject*>(root, QString("button"));
if(button) {
MyType *mytype = new MyType;
QObject::connect(button, SIGNAL(clicked()), mytype,
SLOT(doSomething()));
}
graphicsView->show();
return a.exec();
}
#include "main.moc"
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
res.qrc
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<RCC>
<qresource prefix="/">
<file>myqml.qml</file>
</qresource>
</RCC>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
myqml.qml
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import Qt 4.7
//import MyType 1.0
Item {
id: screen
width: 500; height: 500;
Rectangle {
id: button
signal clicked
width: 200; height: 200; color: "red"
MouseArea {
anchors.fill: parent
onClicked: {
button.color = "blue";
button.clicked();
}
}
}
// MyType {
// id: mytype1
// }
// Connections {
// target: button
// onClicked: ??????
// }
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
QMLConnectTest.pro
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
QT += core gui declarative
TARGET = QMLConnectTest
TEMPLATE = app
RESOURCES += res.qrc
SOURCES += main.cpp
OTHER_FILES += myqml.qml
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
More information about the Qt-interest-old
mailing list