Signal from C++ in QML
-
There is a code like this
@
// interfaceqml.hclass InterfaceQML : public QObject {
Q_OBJECTpublic:
InterfaceQML(QObject *parent = 0);
int t;signals:
void newSignal(int i);public slots:
void newSlot();
};
@InterfaceQML::InterfaceQML(QObject *parent) : QObject(parent) {
t = 0;
}void InterfaceQML::newSlot() {
emit newSignal(t); t++;
}
@class MainWindow : public QObject {
Q_OBJECT
public:
MainWindow(QObject *parent = 0);
InterfaceQML *interface;
QQuickView *view;
QTimer *timer;
};
@MainWindow::MainWindow(QObject *parent) : QObject(parent) {
interface = new InterfaceQML;
timer = new QTimer;
view = new QQuickView;qmlRegisterType<InterfaceQML>("Interface", 1, 0, "Interface"); view->setSource(QUrl("file:/main.qml")); view->show(); QObject *pObject = view->rootObject(); connect(timer, SIGNAL(timeout()), interface, SLOT(newSlot())); timer->start(500);
}
@import QtQuick 2.0
import Interface 1.0Rectangle {
width: 500
height: 500
color: "#748596"signal sgSignal() Text { id: text anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter text: "World" font.bold: true font.pointSize: 30 color: "red" } Interface { onNewSignal: { text.text = i } }
}
@But signal not reach QML. How fix it?
-
You are instantiation 2 separate Interface objects: one in C++, and another in QML. No wonder it does not work. Get a pointer to your QML instance using QObject::findChildren() (just remember that findChildren requires your QML object to be named in "objectName" property for the method to work) or use a timer in QML and trigger it from there.
There are a few other ways to do it, but I won't flood you with information right now.
-
So I did.
InterfaceQML::InterfaceQML(QObject *parent) : QObject(parent) { t = 0; emit newSignal(t); } ...
@
MainWindow::MainWindow(QObject *parent) : QObject(parent) {
timer = new QTimer;
view = new QQuickView;qmlRegisterType<InterfaceQML>("Interface", 1, 0, "Interface"); view->setSource(QUrl("file:/main.qml")); view->show(); QObject *pObject = view->rootObject(); InterfaceQML *interface = pObject->findChild<InterfaceQML *>(); connect(timer, SIGNAL(timeout()), interface, SLOT(newSlot())); timer->start(500);
}
@Thanks