Qt文档阅读笔记-C++与QML混合编程(QML画饼状图)【通过信号与槽交互】

这里只点名一点:

Qt Charts是利用Qt的图形视图框架(QGraphics)搞出来的,底层并不是用OPenGL,而QML却与OPenGL的底层紧密关联

 

运行截图如下:

 

源码如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    void addBtnClicked();
    void reduceBtnClicked();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->quickWidget->setSource(QUrl("qrc:/chart.qml"));

    QObject *pRoot = (QObject*)ui->quickWidget->rootObject();
    Q_ASSERT(pRoot);

    connect(ui->addPushButton,SIGNAL(clicked()),pRoot,SIGNAL(addEaten()));
    connect(ui->reducePushButton,SIGNAL(clicked()),pRoot,SIGNAL(reduceEaten()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::addBtnClicked()
{
    ui->quickWidget->update();
}

void Widget::reduceBtnClicked()
{
    ui->quickWidget->update();
}

chart.qml

import QtQuick 2.0
import QtCharts 2.0

Rectangle {
    id: root

    ChartView {
        width: parent.width
        height: parent.height
        theme: ChartView.ChartThemeBrownSand
        antialiasing: true

        PieSeries {
            id: pieSeries
            PieSlice { id: eaten;  label: "eaten"; value: 94.9 }
            PieSlice { id: unEaten; label: "not yet eaten"; value: 5.1 }
        }
    }

    signal addEaten
    signal reduceEaten

    onAddEaten: {
        eaten.value += 1.5
        unEaten.value -= 1.5
    }

    onReduceEaten: {
        eaten.value -= 1.5
        unEaten.value += 1.5
    }

}

 

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页