简体   繁体   中英

QT5.3 How can I add my Qobject to the QQmlEngine and access it's Properties via QML?

I'm starting out with QT5.3, or rather QT in general. Now I basically want to program C/C++ console applications and add a front-end.

I created a QT Quick Application and have trouble getting my back-end code to interact with the front-end.

What I have so far:

Main.qml :

import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Controls 1.2

Window {
    visible: true
    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
          //  Qt.quit();
        }
    }

    Text {
        text: w1.getRoll
        anchors.centerIn: parent
    }

    Button {
        onClicked: w1.roll
    }


}

Main.cpp :

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "wuerfel.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    Wuerfel w1;

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    engine.setContextForObject(&w1,engine.rootContext());

    return app.exec();
}

Wuerfel.h :

#ifndef WUERFEL_H
#define WUERFEL_H

#include <QObject>
#include <time.h>
#include <cstdlib>

class Wuerfel : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString w1 READ getRoll WRITE roll NOTIFY rolled)
public:
    explicit Wuerfel(QObject *parent = 0);
    void roll(){
        srand((unsigned) time(NULL));
        head = rand() % 6 + 1;

        emit rolled();
    }

    int getRoll(){
        return head;
    }

signals:
    void rolled();

public slots:

private:
    int head;
};

#endif // WUERFEL_H

Debug Error

调试错误

I have no clue what I have to do. The Documentation and web search results with similar issues confuse me even more. They mention QQView or QComponent etc. but whenever I try one of their solutions, something is missing. Like the method mentioned is not part of the object, so it's not found etc.

Has anyone a clue how to get this working? I want to use this approach to visualize future console applications from a C++ tutorial. And developing front-ends in QT in general.

Thanks in Advance. =)

您可以使用QQmlContext::setContextProperty为根上下文设置name属性的值:

engine.rootContext()->setContextProperty("w1",  &w1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM