Qt World Summit: Submit your Presentation

Error when using C++ class Linked to QML

  • iam using Qt Quick Control 2 in Qt 5.7 iam try to connect a c++ class to qml i use this code in main

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlEngine>
    #include <QQmlContext>
    #include "mainwindow.h"
    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        qputenv("QT_QUICK_CONTROLS_STYLE", "Flat");
        QScopedPointer<MainWindow> MyClass(new MainWindow);
        QQmlApplicationEngine engine;
        return app.exec();

    the class i use

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QObject>
    #include <QPoint>
    class MainWindow : public QObject
        explicit MainWindow(QObject *parent = 0);
        Q_INVOKABLE void check();
    #endif // MAINWINDOW_H

    and .cpp

    #include "mainwindow.h"
    #include <QDebug>
    MainWindow::MainWindow(QObject *parent) :
    void MainWindow::check()
        qDebug() << "hello";

    i can't use the MyClass in qml when i use it i get error on the line i use in qml file


    import QtQuick 2.4
    import QtQuick 2.5
    import QtQuick.Controls 2.0
    import QtQuick.Dialogs 1.2
    import QtQuick.Layouts 1.1
    import QtQuick.Window 2.0
    ApplicationWindow {
        id: window
        width: 480
        height: 480
        title: "Flat Example"
        visible: true
        MainForm {
            id: amr
            visible: true
            text3.x: amr.width / 2 - 60
            MyClass.check() // i got error here red line under this 

    when i try to run i got

    qrc:/Main.qml:19 Syntax error

    so what i do wrong ?
    Thanks in Advance

  • Hi! "MyClass.check()" is a function call. But that's not allowed there.

  • @Wieland what should i do to use this function from c++ class ?

  • That depends. When do you want to call the function?

  • @Wieland Thank you it solve i add it to button function

            button1.onClicked: {

  • @AmrCoder

    First post.

    You stole my Class. Amazingly this is word for word for what I'm doing at the moment with the exception of the qputenv(). Must check that! And I had the same problem and solved it in the same manner. I've just returned to programming after several years out of the game,

Log in to reply