QT之C++和QML混合编程学习笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zym326975/article/details/84136986

QML中使用C++对象

创建一个测试用的C++对象

#ifndef PIECHART_H
#define PIECHART_H
#include <QtQuick/QQuickPaintedItem>
#include <QColor>
#include <QPainter>

class PieChart : public QQuickPaintedItem
{
    Q_OBJECT

    Q_PROPERTY(QString name READ name WRITE setName)
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
public:
    PieChart(QQuickItem *parent=0);
    QString name() const;
    void setName(const QString &name);
    QColor color() const;
    void setColor(const QColor &color);
    void paint(QPainter *painter);

    Q_INVOKABLE void clearChart();

signals:
    void chartCleared();
    void colorChanged();

public:
    QString myName;
    QColor myColor;
};

#endif // PIECHART_H
#include "piechart.h"

PieChart::PieChart(QQuickItem *parent)
    :QQuickPaintedItem(parent)
{

}

QString PieChart::name() const
{
    return myName;
}

void PieChart::setName(const QString &name)
{
    myName = name;
}

QColor PieChart::color() const
{
    return myColor;
}

void PieChart::setColor(const QColor &color)
{
    if (color != myColor)
    {
       myColor = color;
       update();   // repaint with the new color
       emit colorChanged();
    }
}

void PieChart::paint(QPainter *painter)
{
    QPen pen(myColor, 2);
    painter->setPen(pen);
    painter->setRenderHints(QPainter::Antialiasing, true);
    painter->drawPie(boundingRect().adjusted(1, 1, -1, -1), 90 * 16, 290 * 16);
}

void PieChart::clearChart()
{
    setColor(QColor(Qt::transparent));
    update();
    emit chartCleared();
}

将C++对象注册到QML中 

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <piechart.h>

int main(int argc, char *argv[])
{
   QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
   QGuiApplication app(argc, argv);
   //4个参数的含义是,包名,主版本号,此版本好,QML类型名
   qmlRegisterType<PieChart>("Charts",1,0,"PieChart");
   QQmlApplicationEngine engine;
   engine.load(QUrl(QLatin1String("qrc:/main.qml")));
   return app.exec();
}

在QML中使用C++注册到QML中的对象

import QtQuick 2.7
import QtQuick.Controls 1.4
import Charts 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Row {
         anchors.centerIn: parent
         spacing: 20

         PieChart {
             id: chartA
             width: 100; height: 100
             color: "red"
         }

         PieChart {
             id: chartB
             width: 100; height: 100
             color: chartA.color
         }
     }

     MouseArea {
         anchors.fill: parent
         onClicked: { chartA.color = "blue" }
     }

    Text {
        anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }
        text: "Click anywhere to clear the chart"
    }
}

 C++中使用QML对象

从C++中加载QML对象

ApplicationWindow {
    objectName: "window"
    id: window
    visible: true
    width: 640
    height: 480
    property int someNumber: 100
    title: qsTr("Hello World")

    signal qmlSignal(string msg)

    Item {
        objectName: "item"
        width: 100
        height: 100

        Rectangle {
            anchors.fill: parent
            border.width: 1
        }
    }

    function myQmlFunction(msg) {
        console.log("Got Message",msg);
        return "some return value"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: window.qmlSignal("Hello from QML")
    }
}
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlProperty>
#include <QList>
#include <QDebug>
#include <QMetaObject>

#include <QQmlComponent>
#include <myclass.h>
#include <QQuickView>
#include <QQuickItem>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    QList<QObject *> rootObjects = engine.rootObjects();
    int count = rootObjects.size();

    QObject *root = NULL;
    for(int i=0;i<count;i++)
    {
        if(rootObjects.at(i)->objectName() == "window")
        {
            root = rootObjects.at(i);
            break;
        }
    }

    MyClass myClass;
    QObject::connect(root, SIGNAL(qmlSignal(QString)),
                     &myClass,SLOT(cppSlot(QString)));

    QVariant returnedValue;
    QVariant msg = "Hello from C++";
    QMetaObject::invokeMethod(root, "myQmlFunction",
                              Q_RETURN_ARG(QVariant,returnedValue),
                              Q_ARG(QVariant,msg));
    qDebug() << "QML function returned:" << returnedValue.toString();

    qDebug() << "Property value:" << QQmlProperty::read(root, "someNumber").toInt();
    QQmlProperty::write(root, "someNumber", 5000);

    qDebug() << "Property value:" << root->property("someNumber").toInt();
    root->setProperty("someNumber", 100);
    QObject *item = root->findChild<QObject*>("item");
    if(item)
    {
        item->setProperty("width", "400");
    }
    //delete root;

    return app.exec();
}

猜你喜欢

转载自blog.csdn.net/zym326975/article/details/84136986