2017-06-13 97 views
0

有一段時間我以爲我無法將Qt C++類與qml應用程序一起使用,但我發現這是:http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html如何從qt C++類創建一個qml對象

現在我試圖創建一個可實例化的對象類型。我第一次遇到「Qwidget:無法創建沒有QApplication的Qwidget」在線閱讀,答案似乎只是將QGuiApplication更改爲QApplication,但後來我得到:「ASSERT:」 !d-> isWidget「

This是,我想作爲一個QML類型使用Qt的類:http://doc.qt.io/qt-5/qlcdnumber.html

這裏是我的main.cpp:

#include <QApplication> 
#include <QQmlApplicationEngine> 
#include <QLCDNumber> 
#include <QQuickStyle> 
int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 

    QQmlApplicationEngine engine; 
    qmlRegisterType<QLCDNumber>("LCDNumber",1,0,"LCDNumber"); 
    engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); 

    if (engine.rootObjects().isEmpty()) 
     return -1; 


    return app.exec(); 
} 

這裏是我想在main.qml創建:

... 
import LCDNumber 1.0 
Window { 

    ... 

    LCDNumber{ 
     digitCount: 3 
     intValue: 1 
     mode: LCDNumber.Dec 
     segmentStyle: LCDNumber.Flat 
     smallDecimalPoint: false 
     value: 0 
    } 
} 

真的可以在qml中創建一個qt C++類嗎?我錯過了什麼?

+1

http://doc.qt.io/qt-5/qtqml-tutorials-extending-qml-example.html – AlexanderVX

+0

你在混合'Qt'和'QtWidget'和'QtQuick2'。 'QtWidget'和'QtQuick2'都是'Qt'的一部分(Qt'只有這兩個)。僅僅因爲你不能將'QtWidget'集成到'QtQuick'並不意味着你不能集成'Qt'中的任何東西。很多 - 例如許多模型 - 很容易集成到qml中。 – derM

回答

2

是的,這是可能的!

在您的課堂上使用的標籤Q_PROPERTY和Q_INVOKABLE提供到QML訪問的屬性和方法的類,像這樣:

class NameYourClass : public QDeclarativeItem { 
    Q_OBJECT 
    Q_PROPERTY(int intProperty1 READ getIntProperty1 WRITE setIntProperty1) 
    Q_PROPERTY(QString strProperty2 READ getStrProperty2 WRITE setStrProperty2) 

private: 
    int intProperty1; 
    QString strProperty2; 

public: 
    explicit NameYourClass(QDeclarativeItem *parent = 0); 
    ~NameYourClass(); 

    Q_INVOKABLE int getIntProperty1() const; 
    Q_INVOKABLE void setIntProperty1(int value); 

    Q_INVOKABLE QString getStrProperty2() const; 
    Q_INVOKABLE void setStrProperty2(const QString &value); 
} 

你的main.cpp:

int main(int argc, char *argv[]) { 
    QApplication app(argc, argv); 

    qmlRegisterType<NameYourClass>("IdentifierName", 1, 0, "NameYourClass"); 

    return app.exec(); 
} 

您的QML文件:

import IdentifierName 1.0 

Rectangle { 
    id: nameRectangle 
    width: 999 
    height: 999 

    onSomethingChange: { 
     execFunction(); 
    } 

    property NameYourClass nameDesired: nameObject 

    NameYourClass { 
     id: nameObject 
     intProperty1: 999 
    } 

    function execFunction() { 
     var varExample; 
     varExample = nameDesired.getIntProperty1(); 
     nameDesired.setIntProperty1(varExample); 
    } 
} 

我不認爲我已經忘記了任何東西。

我希望它有幫助!

+0

您是否知道是否有辦法將此功能添加到現有的Qt C++類中,例如:「http://doc.qt.io/qt-4.8/qlcdnumber.html」。也許使用一個包裝或類似的東西? –

+0

僅當類Qt可以擴展爲子類時才使用。否則,這是不可能的。 – msribeir