I am new to Qt and am currently trying to connect a c++ part of my program with the qml part. The goal of th connection is to pass the currently selected item of a TreeView to qml (possibly via on_treeView_doubleClicked). Since that didnt work I tried all the suggested connections on here for a very basic programm, but I am always receiving the following error:
file::/main.qml:10: ReferenceError: test is not defined
This is the piece of my code regarding the connection:
test.h:
#ifndef TEST_H
#define TEST_H
#include <QObject>
#include <QDebug>
class test : public QObject
{
Q_OBJECT
public:
explicit test(QObject *parent = nullptr);
Q_INVOKABLE void testFunc();
signals:
public slots:
};
#endif // TEST_H
test.cpp:
#include "test.h"
test::test(QObject *parent) : QObject(parent)
{
}
void test::testFunc()
{
qDebug() << "Hello from C++!";
}
mainwindow.cpp:
test testObj;
QQmlApplicationEngine engine;
ui->quickWidget->setSource(QUrl::fromLocalFile(":/main.qml"));
engine.rootContext()->setContextProperty("test", &testObj);
main.qml:
import QtQuick 2.0
import QtQuick.Window 2.3
Item {
Timer{
id: timer
interval: 1000; running: true; repeat:true
onTriggered:{
console.log("ex")
test.testFunc();
}
}
}
I would be really thankful for any help (not only for the simple programm, but possibly for passing the currently selected item of my treeView). I know there a a couple suggestions in other threads, but they dont seem to work for me, so please dont mark this as duplicate.
Thanks in advance,
Lucas
qmlRegisterType<test>("com.mycompany.testing", 1, 0, "test");
See documentation. Note that in your case alsoqmlRegisterSingletonType
is needed (you are exposing some object to QML). – Marek R