QT之QML从入门到精通(第九章)
来源:华佗健康网
Timer使用
import QtQuick 2.12 //2.15
import QtQuick.Window 2.12 //2.15
import QtQuick.Controls 2.12 //可以引入别的控件
import Qt.labs.folderlistmodel 2.12
import Qt.labs.platform 1.0 as Platform
//import QtQuick.Layouts 1.15
Window{
id:window
width:800
height:600
title: ""
visible :true
property int time: 0
Timer{
id:timer
interval: 1000
repeat: true //true不断被触发。
onTriggered: {
time ++;
}
running: true //启动定时器
triggeredOnStart: true //立刻调用一次
}
Text {
id: txt
text: time
font.pixelSize: 30
anchors.centerIn: parent
}
Button{
id:btn
width: 100
height: 50
onClicked: {
timer.start() //开启定时器,如果正在启动则无效果。 restart重新启动 stop停止定时器
}
}
}
自定义Model
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "mylistmodel.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//加载之前注册函数。在加载qml之前注册
// 是一个用于将 C++ 对象或值暴露给 QML 环境的方法。通过这个方法,你可以在 QML 中直接访问和操作 C++ 对象的属性和方法,实现 C++ 与
engine.rootContext()->setContextProperty("MyListModel",MyListModel::getInst());
// qmlRegisterSingletonInstance("MyModel",1,0,"MyListModel",MyListModel::getInst() ); //本人这里没有这个类型
// qmlRegisterType<MyListModel>("MyObj",1,0,"MyListModel"); //通过模板创建
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);
return app.exec();
}
mylistmodel.h
#ifndef MYLISTMODEL_H
#define MYLISTMODEL_H
#include <QAbstractListModel>
class MyData
{
public:
QString m_string;
int m_val;
MyData(QString s,int v):m_string(s),m_val(v)
{
}
};
class MyListModel : public QAbstractListModel
{
Q_OBJECT
public:
enum MyRoleName
{
Name = Qt::DisplayRole +1,
Value
};
static MyListModel* getInst();
explicit MyListModel(QObject *parent = nullptr);
// Header:
// QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
// Basic functionality:
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int,QByteArray>roleNames() const override;
private:
// QList<QString> m_data;
QList<MyData> m_data;
};
#endif // MYLISTMODEL_H
mylistmodel.cpp
#include "mylistmodel.h"
#define qtstr(s) QString::fromLocal8Bit(s)
MyListModel* MyListModel::getInst()
{
// static MyListModel model;
// return &model;
static MyListModel* model = new MyListModel;
return model;
}
MyListModel::MyListModel(QObject *parent)
: QAbstractListModel(parent)
{
// m_data.append(qtstr("张三"));
// m_data.append(qtstr("李四"));
// m_data.append(qtstr("王五"));
m_data.append(MyData("zs",10));
m_data.append(MyData("ls",20));
m_data.append(MyData("ww",40));
}
//QVariant MyListModel::headerData(int section, Qt::Orientation orientation, int role) const
//{
// // FIXME: Implement me!
//}
int MyListModel::rowCount(const QModelIndex &parent) const
{
// For list models only the root node (an invalid parent) should return the list's size. For all
// other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
if (parent.isValid())
return 0;
// FIXME: Implement me!
return m_data.count();
}
QVariant MyListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
// FIXME: Implement me!
if(role == MyRoleName::Name)
{
return m_data[index.row()].m_string;
}
else if(role == MyRoleName::Value)
{
return m_data[index.row()].m_val;
}
return QVariant();
}
QHash<int, QByteArray> MyListModel::roleNames() const
{
QHash<int,QByteArray> roles;
roles.insert(MyRoleName::Name,"name"); //字符串qml端使用
roles.insert(MyRoleName::Value,"value"); //枚举C++进行判断
return roles;
}
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
//import MyObj 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListView
{
width: 200
height: 300
model:MyListModel
delegate: Text
{
id: text
text: name +" " +value
}
}
}
ChartView控件使用
这个控件不支持在QGuiApplication控件绘制,需要使用Qapplication控件调用
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ChartView
{
width: 400
height: 300
theme: ChartView.ChartThemeBrownSand //主题,棕色 沙子
antialiasing: true //抗锯齿
PieSeries
{
id:pieseries
PieSlice{label: "eaten" ;value: 99}
PieSlice{label: "test" ;value: 45 } //扇形片
}
}
}
PieSeries
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ChartView
{
width: 400
height: 300
theme: ChartView.ChartThemeBrownSand //主题,棕色 沙子
antialiasing: true //抗锯齿
PieSeries //饼状图序列
{
id:pieseries
PieSlice
{
label: "eaten" ;value: 99 ;labelVisible: true
borderColor: "transparent"
borderWidth: 0
exploded: true //远离饼状图
labelArmLengthFactor: 0; //控制label距离。
// angleSpan //只读属性,获取角度的,总计360°
} //根据value计算比例
PieSlice{label: "test" ;value: 45 } //扇形片
}
}
}
LineSeries
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3
import QtQuick.Controls 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property var linePoints :[Qt.point(10,10),Qt.point(20,20)]
property var lines: [[0,0,12,13,23,20],[35,26,40,12] ]
ChartView {
id:charview
title: "Line"
anchors.fill: parent
antialiasing: true
ValueAxis{
min:0
max:50
id:xAxis
}
ValueAxis{
min:0
max:40
id:yAxis
minorTickCount: 3 //每个值直接需要绘制多少条虚线
tickCount: 10 //多少个值显示
}
}
Button{
width: 100
height: 50
id:btn
x:500
onClicked: {
// 饼图
// var pie = charview.createSeries(ChartView.SeriesTypePie,"Mypipe")
// pie.append("pie",50)
// pie.append("pie",50)
//折线图
// var line = charview.createSeries(ChartView.SeriesTypeLine,"MyLine",xAxis,yAxis)
// line.append(10,10)
// line.append(20,20)
// for(var i=0;i<linePoints.length ;i++)
// {
// line.append(linePoints[i].x,linePoints[i].y)
// }
for(var i=0;i<lines.length;i++)
{
var points = lines[i]
// ChartView.SeriesTypeSpline // 曲线
var line = charview.createSeries(ChartView.SeriesTypeLine,"MyLine",xAxis,yAxis)
for(var j=0;j<points.length;j++)
{
line.append(points[j],points[j+1])
}
}
}
}
}
AreaSeries
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3
import QtQuick.Controls 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ChartView{
id:chartview
title: "my chartview"
anchors.fill: parent
antialiasing: true
LineSeries{
id:l1
name:"lineseries1"
XYPoint { x: 0; y: 0 }
XYPoint { x: 1.1; y: 2.1 }
XYPoint { x: 1.9; y: 3.3 }
XYPoint { x: 2.1; y: 2.1 }
XYPoint { x: 2.9; y: 4.9 }
XYPoint { x: 3.4; y: 3.0 }
XYPoint { x: 4.1; y: 3.3 }
}
LineSeries{
id:l2
name:"lineseries2"
XYPoint { x: 0; y: 0 }
XYPoint { x: 1.1; y: 1.1 }
XYPoint { x: 1.9; y: 2.3 }
XYPoint { x: 2.1; y: 1.1 }
XYPoint { x: 2.9; y: 3.9 }
XYPoint { x: 3.4; y: 2.0 }
XYPoint { x: 4.1; y: 2.3 }
}
Component.onCompleted: {
//填充区域
var area = chartview.createSeries(ChartView.SeriesTypeArea,"myarea")
area.upperSeries = l2 //上限
area.lowerSeries = l1 //下限
area.opacity = 0.3
area.color = "lightsteelblue"
}
}
}
BarSeries
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3
import QtQuick.Controls 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ChartView {
id:chartview
title: "Bar series"
anchors.fill: parent
legend.alignment: Qt.AlignBottom
antialiasing: true
BarCategoryAxis{ //坐标系
id:axisX
categories: ["2007", "2008", "2009", "2010", "2011", "2012" ]
}
// BarCategoryAxis{ //坐标系
// id:axisY
// categories: ["0", "0.1", "0.2", "0.3", "0.6", "0.9" ]
// }
ValueAxis{ //要使用value的坐标系,不能使用Bar的坐标系
id:axisY
min:0
max:2
}
// BarSeries {
// id: mySeries
// axisX: BarCategoryAxis { categories: ["2007", "2008", "2009", "2010", "2011", "2012" ] }
// BarSet { label: "Bob"; values: [2, 2, 3, 4, 5, 6] }
// BarSet { label: "Susan"; values: [5, 1, 2, 4, 1, 7] }
// BarSet { label: "James"; values: [3, 5, 8, 13, 5, 8] }
// }
Component.onCompleted: {
var barseries = chartview.createSeries(ChartView.SeriesTypeBar,"mytype",axisX,axisY)
barseries.append("mybar1",[0,0.2,0.2,0.5,0.4,1.5,0.9])
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容