0
votes

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

1
qmlRegisterType<test>("com.mycompany.testing", 1, 0, "test"); See documentation. Note that in your case also qmlRegisterSingletonType is needed (you are exposing some object to QML).Marek R

1 Answers

1
votes

You have 3 main errors:

  • If you are going to use a .qml from a qresource you should not use QUrl::fromLocalFile() since the qresource is not a local file but virtual.

  • testObj is a local variable so it will be eliminated as soon as the function where it was created is finished, one solution is to make testObj a member of the class.

  • And for the last one, the main error, QQuickWidget already has a QQmlEngine, you do not have to create another one.


*.h

Ui::MainWindow *ui;
test testObj;

*.cpp

ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
ui->quickWidget->engine()->rootContext()->setContextProperty("test", &testObj);

My full test can be found at the following link