0

我从 QT5.3 开始,或者更确切地说是 QT。现在我基本上想编写 C/C++ 控制台应用程序并添加一个前端。

我创建了一个 QT 快速应用程序,但无法让我的后端代码与前端交互。

到目前为止我所拥有的:

主要.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
    }


}

主要.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();
}

乌尔费尔.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

调试错误

调试错误

我不知道我必须做什么。具有类似问题的文档和网络搜索结果让我更加困惑。他们提到QQViewQComponent等等,但每当我尝试他们的解决方案之一时,都会缺少一些东西。就像提到的方法不是对象的一部分,所以它没有找到等等。

有谁知道如何让这个工作?我想使用这种方法从 C++ 教程中可视化未来的控制台应用程序。并且一般在 QT 中开发前端。

提前致谢。=)

4

1 回答 1

1

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

engine.rootContext()->setContextProperty("w1",  &w1);
于 2014-08-24T12:04:10.347 回答