QMLとC++の混和プログラミング

46167 ワード

文書ディレクトリ
  • QMLとC++の混和プログラミング
  • QMLでC++クラス
  • を使用
  • 1、まずcppにQMLタイプ
  • を登録する
  • 2、QMLファイルにカスタムQMLタイプ
  • を含める
  • 3、クラスはQから継承するOBJECT
  • 4、Q_PROPERTY属性説明
  • 5、Q_INVOKABLEマクロ
  • 6、カスタム属性Q_INVOKABLEマクロ説明
  • C++でQMLクラス
  • を使用
  • 1、QQQmlComponentを使用してQMLオブジェクト
  • を作成する
  • 全コード
  • QMLとC++の混和プログラミング
    	 QT              ,          。
               。             ,PPT  
            ,    QSS    ,QSS  CSS,    
    CSS      ,          ,          
    QML    ,      QML   ,C++    ,     
    QT     。        ,     QML       
        ,  C++         QT        。
            Q_OBJECT  !
    

    QMLでのC++クラスの使用
    1、まずcppにQMLタイプを登録する
    //qmlRegisterType  C++   QML
    //arg1:import    
    //arg2:    
    //arg3:    
    //arg4:QML   
    qmlRegisterType<Colors>("MyCppObject",1,0,"CppObject");
    

    2、QMLファイルにカスタムQMLタイプを含める
    import MyCppObject 1.0
    

    3、クラスはQ_から継承するOBJECT
    4、Q_PROPERTYプロパティの説明
    5、Q_INVOKABLEマクロ
    #include 
    
    class Colors : public QObject
    {
        Q_OBJECT
    
        //    ,     QML   --           
        Q_PROPERTY(QString name READ getName WRITE setName)
        Q_PROPERTY(int year READ getYear WRITE setYear NOTIFY yearChanged)
    
    public:
        explicit Colors(QObject *parent = nullptr);
    
        //  Q_INVOKABLE    public     QML   
        Q_INVOKABLE void sendSignal();//       
    
    

    6、カスタム属性Q_INVOKABLEマクロ説明
    Q_PROPERTY(type name
       READ getFunction
       [WRITE setFunction]
       [RESET resetFunction]
       [NOTIFY notifySignal]
       [DESIGNABLE bool]
       [SCRIPTABLE bool]
       [STORED bool]
       [USER bool]
       [CONSTANT]
       [FINAL])
    	   /*
    	                  :
    		Q_PROPERTY(double minValue READ getMinValue WRITE setMinValue)
    		Q_PROPERTY(bool animation READ getAnimation WRITE setAnimation)
    		Q_PROPERTY(QColor barColor READ getBarColor WRITE setBarColor)
    	  */
    	  /*
    		 Q_PROPERTY(    
    		 getFunction
    		( setFunction)
    		(  resetFunction)
    		(  notifySignal)
    		(     bool)
    		(  bool)
    		(  bool)
    		(  bool)
    		(  )
    		[  ])
    	  */
    

    C++でのQMLクラスの使用
    1、QQQmlComponentを使用してQMLオブジェクトを作成する
        QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
        QObject* object = component.create();
    
        Colors *col = new Colors();
        QObject::connect(object, SIGNAL(qmlSignalA()),
                           col, SLOT(cppSlotmy()));
    

    すべてのコード
    //**ColorText.qml**
    Item {
        id: root
        property string colorText //           
        property alias textFont1: text1.font //                 
        signal clicked(string buttonColor)   //                   
    
        //        
        function changeDuration(duration) {
            animation.duration = duration
            animation1.duration = duration/10
        }
    
        Text {
            id: text1
            text: colorText
            anchors.centerIn: parent
            Behavior on rotation {
                NumberAnimation {
                    id: animation
                    duration: 500
                }
            }
        }
    
        Rectangle {
            id: colorRect
            width: 20 * 2
            height: width
            //radius: 20
            border.color: "green"
    
            //   text1   ,   10, text1     
            anchors.left: text1.right
            anchors.leftMargin: 10
            anchors.verticalCenter: text1.verticalCenter
    
            //            
            Behavior on width {
                NumberAnimation {
                    id: animation1
                    duration: 50
                }
            }
    
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    console.debug("colorRect: ", parent.border.color)
                    text1.rotation += 360
                    text1.color = parent.border.color
                    root.clicked(parent.border.color)   //              
                }
    
                hoverEnabled: true
                onEntered: {
                    parent.width = 32
                    parent.color = "black"
                }
                onExited: {
                    parent.width = 40
                    parent.color = "white"
                }
            }
    
            Rectangle {
                width: 12 * 2
                height: width
                radius: 12
                color: parent.border.color
                anchors.centerIn: parent
            }
        }
    
        Rectangle {
            id: colorRect2
            width: 20 * 2
            height: width
            radius: 20
            border.color: "red"
    
            //   text1   ,   10, text1     
            anchors.bottom: text1.top
            anchors.bottomMargin: 10
            anchors.horizontalCenter: text1.horizontalCenter
    
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    console.debug("colorRect: ", parent.border.color)
                    text1.rotation += 360
                    text1.color = parent.border.color
                    root.clicked(parent.border.color)
                }
    
                hoverEnabled: true
                onEntered: {
                    parent.width = 32
                    parent.color = "black"
                }
                onExited: {
                    parent.width = 40
                    parent.color = "white"
                }
            }
    
            Rectangle {
                width: 12 * 2
                height: width
                radius: 12
                color: parent.border.color
                anchors.centerIn: parent
            }
        }
    
        Rectangle {
            id: colorRect3
            width: 20 * 2
            height: width
            radius: 20
            border.color: "blue"
    
            //   text1   ,   10, text1     
            anchors.right:  text1.left
            anchors.rightMargin: 10
            anchors.verticalCenter: text1.verticalCenter
    
            MouseArea {
                anchors.fill: parent
    
                onClicked: {
                    console.debug("colorRect: ", parent.border.color)
                    text1.rotation += 360
                    text1.color = parent.border.color
                    root.clicked(parent.border.color)
                }
    
                hoverEnabled: true
                onEntered: {
                    parent.width = 32
                    parent.color = "black"
                }
                onExited: {
                    parent.width = 40
                    parent.color = "white"
                }
            }
    
            Rectangle {
                width: 12 * 2
                height: width
                radius: 12
                color: parent.border.color
                anchors.centerIn: parent
            }
        }
    }
    
    import QtQuick 2.12
    import QtQuick.Window 2.12
    import MyCppObject 1.0
    
    Window {
        id: root
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        signal qmlSignalA()
        signal qmlSignalB(string str,int value)
    
        Image {
            id: backImg
            source: "qrc:/img/press.png"
            width: parent.width
            height: parent.height
            anchors.bottom: parent.bottom
            fillMode: Image.PreserveAspectFit //     ;       
        }
    
        ColorText {
            anchors.centerIn: parent
            onClicked: {
                colorText = qsTr("   !")
    
                console.log("colorButton: ", buttonColor)
                var value = buttonColor
                switch (value) {
                case "#ff0000":
                    backImg.source = "qrc:/img/ok.jpg"
                      changeDuration(2000)
                    break
                case "#0000ff":
                    backImg.source = "qrc:/img/press.png"
                    changeDuration(1000)
                    break
                default:
                    changeDuration(500)
                    backImg.source = "qrc:/img/bg1.png"
                }
            }
        }
    
        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            //       
            //  --Cpp    
            //  --Qml    
            onClicked: {
                if(mouse.button===Qt.LeftButton){
                    console.log('----clicked left button')
                    cpp_obj.name="gongjianbo"
                    cpp_obj.year=1992
                    cpp_obj.sendSignal() //  Q_INVOKABLE      
                }else{
                    console.log('----clicked right button')
                    root.qmlSignalA()
                    root.qmlSignalB('0000',9999)
                }
            }
        }
    
        //    QML  
         CppObject{
             id:cpp_obj
             //      QML      
             property int counts: 0
    //         onYearChanged: {
    //             counts++
    //             console.log('qml name changed process')
    //         }
    //         onCountsChanged: {
    //             console.log('qml counts changed process')
    //         }
         }
    
         Component.onCompleted: {
             //               QML    
             //cpp object connect qml object
             cpp_obj.onCppSignalA.connect(function(){console.log('qml signal a process')})
             cpp_obj.onCppSignalB.connect(processB)
             //qml object connect cpp object
             root.onQmlSignalA.connect(cpp_obj.cppSlotA)
             root.onQmlSignalB.connect(cpp_obj.cppSlotB)
         }
    
         function processB(str,value) {
             console.log('qml signal b process',str,value)
         }
    
    }
    
    /*##^## Designer {
        D{i:1;anchors_height:78;anchors_width:172;anchors_x:274;anchors_y:584}D{i:2;anchors_height:578;anchors_width:308;anchors_x:64;anchors_y:390}
    }
     ##^##*/
    
    
    
    #ifndef COLORS_H
    #define COLORS_H
    
    #include 
    
    class Colors : public QObject
    {
        Q_OBJECT
    
        //    ,     QML   --           
        Q_PROPERTY(QString name READ getName WRITE setName)
        Q_PROPERTY(int year READ getYear WRITE setYear NOTIFY yearChanged)
    
    public:
        explicit Colors(QObject *parent = nullptr);
    
        //  Q_INVOKABLE    public     QML   
        Q_INVOKABLE void sendSignal();//       
    
        //          --myName
           void setName(const QString &name);
           QString getName() const;
           //          --myYear
           void setYear(int year);
           int getYear() const;
    
    signals:
          //     QML   
          void cppSignalA();//      
          void cppSignalB(const QString &str,int value);//       
          void yearChanged(int year);
    
    public slots:
          //public      QML   
          void cppSlotA();//       
          void cppSlotmy();//      
          void cppSlotB(const QString &str,int value);//        
    
    private:
        //    
        QString myName;
        int myYear;
    
    };
    
    #endif // COLORS_H
    
    
    #include 
    #include 
    #include "colors.h"
    #include "QDebug"
    #include "QQuickView"
    #include "QObject"
    #include 
    #include 
    #include 
    #include 
    #include "QQmlApplicationEngine"
    
    #define cout qDebug()  << "[" <<__file__>
    #if _MSC_VER >= 1600
    #pragma execution_character_set("utf-8")
    #endif
    
    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        //qmlRegisterType  C++   QML
        //arg1:import    
        //arg2:    
        //arg3:    
        //arg4:QML   
        qmlRegisterType<Colors>("MyCppObject",1,0,"CppObject");
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
        QQuickView view(QUrl("qrc:/main.qml"));
        view.show();
    
        QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
        QObject* object = component.create();
    
        Colors *col = new Colors();
        QObject::connect(object, SIGNAL(qmlSignalA()),
                           col, SLOT(cppSlotmy()));
    
        return app.exec();
    }
    
    
    #include "colors.h"
    #include 
    
    Colors::Colors(QObject *parent) : QObject(parent)
    {
    
    }
    
    void Colors::sendSignal()
    {
        //   ,          
        qDebug()<<"cpp sendSignal method";
        emit cppSignalA();
        emit cppSignalB(myName,myYear);
    }
    
    void Colors::setName(const QString &name)
    {
        qDebug()<<"cpp setName"<<name;
        myName=name;
    }
    
    QString Colors::getName() const
    {
        qDebug()<<"cpp getName";
        return myName;
    }
    
    void Colors::setYear(int year)
    {
        qDebug()<<"cpp setYear"<<year;
        if(year!=myYear){
            qDebug()<<"cpp emit yearChanged";
            myYear=year;
            emit yearChanged(myYear);
        }
    }
    
    int Colors::getYear() const
    {
        qDebug()<<"cpp getYear";
        return myYear;
    }
    
    void Colors::cppSlotA()
    {
        qDebug()<<"cpp slot a";
    }
    
    void Colors::cppSlotmy()
    {
        qDebug()<<"AAAAAAAAAAAAAAAAAAAAAAAAAAA";
    }
    
    void Colors::cppSlotB(const QString &str, int value)
    {
        qDebug()<<"cpp slot b"<<str<<value;
    }