qt qml

qt qml前言本文作为开发QTqml技术总结和常用函数功能总结,不是很适合初学者。初学者参考资源:https://pan.baidu.com/s/1rwOwKOMoON0ffGcSorndew本人收集的资料仅供参考。qml基础qml和quick支持基本类型//QmlboolBinarytrue/falsevaluedouble…

大家好,欢迎来到IT知识分享网。

前言

本文作为开发QT qml 技术总结和常用函数功能总结,不是很适合初学者。

初学者参考资源:百度网盘-链接不存在  本人收集的资料仅供参考。

qml 基础

qml 和 quick支持基本类型

//Qml

bool            Binary true/false value
double          Number with a decimal point, stored in double precision
enumeration     Named enumeration value
int             Whole number, e.g. 0, 10, or -20
list            List of QML objects
real            Number with a decimal point
string          Free form text string
url             Resource locator
var             Generic property type

//Quick

color
font
matrix4x4   A matrix4x4 type is a 4-row and 4-column matrix
quaternion  A quaternion type has scalar, x, y, and z attributes
vector2d    A vector2d type has x and y attributes
vector3d    Value with x, y, and z attributes
vector4d    A vector4d type has x, y, z and w attributes
date        Date value
point       Value with x and y attributes
rect        Value with x, y, width and height attributes
size        Value with width and height attributes

import

//目录导入 控件

import dir 
import dir as alias

//远程导入
import url 

//qmldir有两种格式

1. qml文件列表文件

Button Button1.qml                 //外部可以访问
internal InterButton Button1.qml   //只能内部访问
myJs my.js

2. qml 模块方式导入

module    ExampleModule           //插件模块名称 必须和安装路径一致
singleton Style 1.0 Style.qml     //单实例  在 Style.qml中头添加 pragma Singleton
internal MyPrivateType MyPrivateType.qml
MyScript  1.0 MyScript.js
plugin MyPluginLibrary            //插件名称  dll 或 so
classname <C++ plugin class>  
typeinfo mymodule.qmltypes        //模块类型描述文件
depends MyOtherModule 1.0         //依赖 别的模块

//直接导入qml
import qmlfileName 
//直接导入js
import ...js as MyJS   //as 必须加

//js导入qml
.import QtQtuck.LocalStorage 2.0 as Storage
//js导入js
Qt.include('my.js')
.import "filename.js" as Qualifier

//单实例说明
qml文件 头加上 pragma Singleton
js文件  头加上 .pragma library

属性

//自定义属性
property int a
property int a: 1
//var 可以表示所有类型
property var somelist: [1, 2, 3]
property var someobj: Rectangle{}

//列表属性
states: [
          State { name: "loading" },
          State { name: "running" },
          State { name: "stopped" }
      ]

[default] property list<<objectType>> propertyName

//分组属性
Text {
      //dot notation
      font.pixelSize: 12
      font.b: true
  }

  Text {
      //group notation
      font { pixelSize: 12; b: true }
  }

//属性别名
property alias color: rectangle.border.color
//默认属性

default property var someText
没有声明的属性自动给默认属性
//只读属性
readonly property <propertyType> <propertyName> : <initialValue>

//枚举属性
// MyText.qml
  Text {
      enum TextType {
          Normal,
          Heading
      }
  }

信号和信号处理

//定义信号
signal clicked()
signal activated(real xPosition, real yPosition)

属性改变自动绑定信号处理函数

//发射信号
clicked

//信号处理函数   on + 信号名称  第一个字母大写
onCliecked:{
}

//连接信号
Connections {
    target: mouse
    onClicked: {
    }
}
//连接函数
clicked.connect(function(){})
clicked.disconnect(function(){})

//对象方法
js方法
function() {}
c++
使用 Q_INVOKABLE声明  或  Q_SLOT注册的函数


附加属性和信号处理

可以使用附加类型的 属性和  信号处理

ListView.isCurrentItem

Component.onCompleted: {
}
//附加属性不能在委托对象的子对象使用

属性绑定

height: parent.height
height:someChangeHeight()

height = Qt.binging(function(){})

鼠标事件

//鼠标事件区域 不可见
MouseArea {
}

介绍
MouseArea是一个不可见的项目,通常与一个可见的项目一起使用,以便为该项目提供鼠标处理。通过有效地充当代理,鼠标处理的逻辑可以包含在MouseArea项中

启用属性用于启用和禁用代理项的鼠标处理。当禁用时,鼠标区域对鼠标事件变得透明。

MouseArea是一个不可见的项目,但它有一个可见的属性。当设置为false时,鼠标区域对鼠标事件变得透明

pressed的只读属性指示用户是否在鼠标区域上按住鼠标按钮。此属性通常用于用户界面中属性之间的绑定。containsMouse只读属性指示鼠标光标在鼠标区域上的存在,但是,在默认情况下,只有当鼠标按钮按下时才会出现这种情况;有关详细信息,请参阅containsMouse文档

如果MouseArea与其他MouseArea项的区域重叠,您可以通过将propagateComposedEvents设置为true并拒绝应该传播的事件,选择将单击、双击和压住事件传播到这些其他项。有关详细信息,请参阅propagateComposedEvents文档

默认情况下,MouseArea项只报告鼠标点击,而不报告鼠标光标位置的变化。设置hoverEnabled属性可以确保使用为onPositionChanged、onEntered和onExited定义的处理程序,即使没有按下鼠标按钮,也可以更新containsMouse属性。

属性
acceptedButtons : Qt::MouseButtons
containsMouse : bool
containsPress : bool
cursorShape : Qt::CursorShape
drag
drag.target : Item
drag.active : bool
drag.axis : enumeration
drag.minimumX : real
drag.maximumX : real
drag.minimumY : real
drag.maximumY : real
drag.filterChildren : bool
drag.threshold : real
enabled : bool
hoverEnabled : bool
mouseX : real
mouseY : real
pressAndHoldInterval : int
pressed : bool
pressedButtons : MouseButtons
preventStealing : bool
propagateComposedEvents : bool
scrollGestureEnabled : bool 
信号
canceled()
clicked(MouseEvent mouse)
doubleClicked(MouseEvent mouse)
entered()
exited()
positionChanged(MouseEvent mouse)
pressAndHold(MouseEvent mouse)
pressed(MouseEvent mouse)
released(MouseEvent mouse)
wheel(WheelEvent wheel) 


MouseArea {
          anchors.fill: parent
          acceptedButtons: Qt.LeftButton | Qt.RightButton
          onClicked: {
              if (mouse.button == Qt.RightButton)
                  parent.color = 'blue';
              else
                  parent.color = 'red';
          }
      }
 MouseArea {
      onClicked: {
          if ((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ShiftModifier))
              doSomething();
      }
    onWheel: {
        if(wheel.modifiers & Qt.ControlModifier) {
            scaleChangled(wheel.angleDelta.y > 0 ? 0.1: -0.1)
        }
    }
  }

拖放

简单移动 Drag  DropArea DragEvent

Rectangle {
      id: container
      width: 600; height: 200

      Rectangle {
          id: rect
          width: 50; height: 50
          color: "red"
          opacity: (600.0 - rect.x) / 600

          MouseArea {
              anchors.fill: parent
              drag.target: rect
              drag.axis: Drag.XAxis
              drag.minimumX: 0
              drag.maximumX: container.width - rect.width
          }
      }
  }

拖放
Item {
      width: 200; height: 200

      Rectangle {
          anchors.centerIn: parent
          width: text.implicitWidth + 20; height: text.implicitHeight + 10
          color: "green"
          radius: 5

          Drag.active: dragArea.drag.active
          Drag.dragType: Drag.Automatic
          Drag.supportedActions: Qt.CopyAction
          Drag.mimeData: {
              "text/plain": "Copied text"
          }

          Text {
              id: text
              anchors.centerIn: parent
              text: "Drag me"
          }

          MouseArea {
              id: dragArea
              anchors.fill: parent

              drag.target: parent
              onPressed: parent.grabToImage(function(result) {
                  parent.Drag.imageSource = result.url
              })
          }
      }
  }

 Item {
      width: 200; height: 200

      DropArea {
          x: 75; y: 75
          width: 50; height: 50

          Rectangle {
              anchors.fill: parent
              color: "green"

              visible: parent.containsDrag
          }
      }

      Rectangle {
          x: 10; y: 10
          width: 20; height: 20
          color: "red"

          Drag.active: dragArea.drag.active
          Drag.hotSpot.x: 10
          Drag.hotSpot.y: 10

          MouseArea {
              id: dragArea
              anchors.fill: parent

              drag.target: parent
          }
      }
  }

焦点作用域

activeFocus     //查询当前项目是否获取了焦点

//焦点作用域
Rectangle {
      width: 100; height: 100

      FocusScope {
          id: focusScope
          focus: true

          TextInput {
              id: input
              focus: true
          }
      }
  }

解释:

1 在每个焦点范围内,至少一个Item::focus设置为true。如果设置了多个焦点属性,则设置焦点的最后一个类型将设置焦点,其他类型将取消设置,类似于没有焦点作用域时的情况。

2 当焦点作用域接收活动焦点时,包含焦点集的类型(如果有的话)也接收活动焦点。如果这个类型也是一个FocusScope,代理行为将继续。焦点范围和子焦点项都将设置activeFocus属性。


//强制获取焦点
forceActiveFocus()
此方法将焦点设置在项上,并确保对象层次结构中的所有祖先FocusScope对象也被给予焦点

动态创建object用js

如.qml是从网上加载的需要等待状态变为准备才能创建 object
  var component;
  var sprite;

  function createSpriteObjects() {
      component = Qt.createComponent("Sprite.qml");
      if (component.status == Component.Ready)
          finishCreation();
      else
          component.statusChanged.connect(finishCreation);
  }

  function finishCreation() {
      if (component.status == Component.Ready) {
          sprite = component.createObject(appWindow, {"x": 100, "y": 100});
          if (sprite == null) {
              // Error Handling
              console.log("Error creating object");
          }
      } else if (component.status == Component.Error) {
          // Error Handling
          console.log("Error loading component:", component.errorString());
      }
  }   
如果.qml文件是本地文件
function createSpriteObjects() {
      component = Qt.createComponent("Sprite.qml");
      sprite = component.createObject(appWindow, {"x": 100, "y": 100});

      if (sprite == null) {
          // Error Handling
          console.log("Error creating object");
      }
  }

//Qml字符串创建
var newObject = Qt.createQmlObject('import QtQuick 2.0; Rectangle {color: "red"; width: 20; height: 20}', parentItem, "dynamicSnippet1");


//删除创建对象

id.destroy()
this.destroy()

注册c++类到qml

qml中可以使用c++槽函数和Q_INVOKABLE 修饰的函数
c++中信号例如clicked qml中自动生成 onClicked处理器

注册
qmlRegisterType<Foo>("App", 1, 0, "Foo");  //可实例化
qmlRegisterType<Bar>();                    //不可实例化

Foo {
      bar.baz: "abc"
      Component.onCompleted: print(bar.baz)
}

单实例注册
 qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qjsvalueApi", 1, 0, "MyApi", [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
      Q_UNUSED(engine)
      Q_UNUSED(scriptEngine)

      SingletonTypeExample *example = new SingletonTypeExample();
      return example;
  });
 qmlRegisterSingletonType(QUrl("file:///absolute/path/SingletonType.qml"), "Qt.example.qobjectSingleton", 1, 0, "RegisteredSingleton");

//属性注册
engine.rootContext()->setContextProperty("cardModel", QVariant::fromValue(mylist));
engine.rootContext()->setContextProperty("cardModel", myObj);

全局对象和方法

.pragma library

function post(url, data, callback, errorCallback) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    var sendData = JSON.stringify(data);
    xhr.setRequestHeader("Content-Length", sendData.length);
    xhr.setRequestHeader("Content-Type", "application/json");  //用POST的时候一定要有这句
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            var data = JSON.parse(xhr.responseText);
            if(callback !== undefined) {
                callback(data);
            }
        }
    }
    xhr.onerror = function(){
        if(errorCallback !== undefined) {
            errorCallback()
        }
    }
    xhr.ontimeout = function(){
        if(errorCallback !== undefined) {
            errorCallback()
        }
    }

    xhr.send(sendData);
}

function get(url, data, callback, errorCallback) {
    var xhr = new XMLHttpRequest();

    url += '?'
    for(var key in data) {
        url += key+'='+data[key] + '&'
    }
    print(url)
    xhr.timeout = 5000
    xhr.open("GET", url, true);
    xhr.onreadystatechange = ()=>{
        if (xhr.readyState === XMLHttpRequest.DONE) {
            var data = JSON.parse(xhr.responseText);
            if(callback !== undefined) {
                callback(data);
            }
        }
    }
    xhr.onerror = function(){
        if(errorCallback !== undefined) {
            errorCallback()
        }
    }
    xhr.ontimeout = function(){
        if(errorCallback !== undefined) {
            errorCallback()
        }
    }

    xhr.send();
}



console.log("a is ", a, "b is ", b);
console.assert(x == 12, "This will pass");
console.time("wholeFunction");
console.trace 
gc()        //手动垃圾回收
print() 

globalObject() 全局对象

Qt.全局属性和方法

Qt QML Type 


Properties
application : object
inputMethod : object
platform : object
styleHints : object 
Methods
string atob(data)
binding(function)
string btoa(data)
callLater(function)
callLater(function, argument1, argument2, ...)
color colorEqual(color lhs, string rhs)
object createComponent(url, mode, parent)
object createQmlObject(string qml, object parent, string filepath)
color darker(color baseColor, real factor)
exit(int retCode)
font(object fontSpecifier)
list<string> fontFamilies()
string formatDate(datetime date, variant format)
string formatDateTime(datetime dateTime, variant format)
string formatTime(datetime time, variant format)
color hsla(real hue, real saturation, real lightness, real alpha)
color hsva(real hue, real saturation, real value, real alpha)
object include(string url, jsobject callback)
bool isQtObject(object)
color lighter(color baseColor, real factor)
locale(name)
string md5(data)
matrix4x4(real m11, real m12, real m13, real m14, real m21, real m22, real m23, real m24, real m31, real m32, real m33, real m34, real m41, real m42, real m43, real m44)
bool openUrlExternally(url target)
point point(int x, int y)
string qsTr(string sourceText, string disambiguation, int n)
string qsTrId(string id, int n)
string qsTrIdNoOp(string id)
string qsTrNoOp(string sourceText, string disambiguation)
string qsTranslate(string context, string sourceText, string disambiguation, int n)
string qsTranslateNoOp(string context, string sourceText, string disambiguation)
quaternion(real scalar, real x, real y, real z)
quit()
rect rect(int x, int y, int width, int height)
url resolvedUrl(url url)
color rgba(real red, real green, real blue, real alpha)
size(int width, int height)
color tint(color baseColor, color tintColor)
vector2d(real x, real y)
vector3d(real x, real y, real z)
vector4d(real x, real y, real z, real w) 

Qt.Quick基础

Item

所有可视化项目父类

children  //可视化子类
resources //不可视化子类

//默认属性 data
所有子类自动添加到data  可视化的分配带 childer 其他 resources

clip  锁定到控件宽度内 
enabled : bool
focus : bool
height : real
implicitHeight : real  //没有指定高度 使用
implicitWidth : real

opacity : real
rotation : real
scale : real
smooth : bool

state : string                 //当前状态
states : list<State>            
transform : list<Transform>
transformOrigin : enumeration  //转化中心
transitions : list<Transition> //过度
visible : bool

x : real
y : real
z : real  //堆叠层


childAt(real x, real y)
bool contains(point point)
forceActiveFocus()
forceActiveFocus(Qt::FocusReason reason)
bool grabToImage(callback, targetSize)
object mapFromGlobal(real x, real y)
object mapFromItem(Item item, real x, real y)
object mapFromItem(Item item, real x, real y, real width, real height)
object mapToGlobal(real x, real y)
object mapToItem(Item item, real x, real y)
object mapToItem(Item item, real x, real y, real width, real height)
nextItemInFocusChain(bool forward) 

Component

属性
progress : real
status : enumeration
url : url  
completed()
destruction() 
方法
object createObject(QtObject parent, object properties)
string errorString()
object incubateObject(Item parent, object properties, enumeration mode) 


//定义
Component {
          id: redSquare

          Rectangle {
              color: "red"
              width: 10
              height: 10
          }
}

Component {
    id: redSquare
    url: 'mycomponent.qml'
}
//加载器 Loader
Loader { sourceComponent: redSquare }
Loader { sourceComponent: redSquare; x: 20 }

redSquare.createObject()     //同步创建
redSquare.incubateObject()   //异步创建

Rectangle

通常用作背景色

antialiasing : bool
border
border.width : int
border.color : color
color : color
gradient : any
radius : real 

gradient: Gradient {
    orientation:Gradient.Vertical
    GradientStop { position: 0.0; color: "red" }
    GradientStop { position: 0.33; color: "yellow" }
    GradientStop { position: 1.0; color: "green" }
}

Text

color  颜色
text   内容
clip   裁剪
elide  
Text.ElideNone - the default
Text.ElideLeft
Text.ElideMiddle
Text.ElideRight


font.bold : bool    
font.capitalization : enumeration  //大小写策略
font.family : string
font.hintingPreference : enumeration 
font.italic : bool
font.kerning : bool       //字距调整
font.letterSpacing : real //字符间距
font.pixelSize : int
font.pointSize : real
font.preferShaping : bool  
font.strikeout : bool   //删除线
font.styleName : string
font.underline : bool
font.weight : enumeration
font.wordSpacing : real  //单词间距

verticalAlignment
horizontalAlignment

Text.AlignLeft, Text.AlignRight, Text.AlignHCenter and Text.AlignJustify. The valid values for verticalAlignment are Text.AlignTop, Text.AlignBottom and Text.AlignVCenter

//文本样式
style : enumeration
styleColor : color

FontLoader字体加载

FontLoader {
          id: webFont
          source: "http://www.mysite.com/myfont.ttf"
      }
      Text {
          text: "Fancy font"
          font.family: webFont.name
      }

FontLoader {
      id: loader
      onStatusChanged: if (loader.status == FontLoader.Ready) console.log('Loaded')
  }

Timer 

Timer {
          interval: 500; running: true; repeat: true
          onTriggered: time.text = Date().toString()
}

Flickable

滚动条显示视图 
设置contentWidth, contentHeight 大于 width heigth就会自动添加滚动条

import QtQuick 2.0

  Flickable {
      width: 200; height: 200
      contentWidth: image.width; contentHeight: image.height

      Image { id: image; source: "bigImage.png" }
  }

LocalStorage 

import QtQuick 2.12
import QtQuick.LocalStorage 2.12

Item {
     Component.onCompleted: {
         var db = openDatabaseSync("QDeclarativeExampleDB", "1.0", "The Example QML SQL!", 1000000);

              db.transaction(
                  function(tx) {
                      // Create the database if it doesn't already exist
                      tx.executeSql('CREATE TABLE IF NOT EXISTS Greeting(salutation TEXT, salutee TEXT)');

                      // Add (another) greeting row
                      tx.executeSql('INSERT INTO Greeting VALUES(?, ?)', [ 'hello', 'world' ]);

                      // Show all added greetings
                      var rs = tx.executeSql('SELECT * FROM Greeting');

                      var r = ""
                      for (var i = 0; i < rs.rows.length; i++) {
                          r += rs.rows.item(i).salutation + ", " + rs.rows.item(i).salutee + "\n"
                      }
                      text = r
                  }
              )


     }
}


 db = Sql.openDatabaseSync(identifier, version, description, estimated_size, callback(db))

Identifier    The name of the database passed to openDatabase()
Version       The version of the database passed to openDatabase()
Description   The description of the database passed to openDatabase()
EstimatedSize The estimated size (in bytes) of the database passed to openDatabase()
Driver        Currently "QSQLITE"


状态 动画 过度

状态

State {
    name: "clicked"
    PropertyChanges { target: myRect; color: "red" }
}

states: [
    State { name: "state1"; when: sharedCondition },
    State { name: "state2"; when: sharedCondition }
]

PropertyChanges 
AnchorChanges
ParentChange
StateChangeScript

StateGroup   //为非item设置

states: State {
                  name: "RINGING"
                  when: (signal.state == "CRITICAL")
                  PropertyChanges {target: speaker; play: "RING!"}
}

动画 

Transition -         状态改变过度动画
SequentialAnimation  串行动画
ParallelAnimation -  并行动画
Behavior -           属性改变动画
PropertyAction -     动画期间 执行 属性改变
PauseAnimation -     暂停动画
SmoothedAnimation -  平滑过度动画
SpringAnimation -    弹簧动画
ScriptAction -       动画期间运行脚本


AnchorAnimation      锚点动画
ColorAnimation       颜色动画
NumberAnimation      数值动画
ParentAnimation      父类改变动画
PathAnimation        路径动画
PropertyAnimation    属性动画
RotationAnimation    旋转动画
Animates changes in rotation values
Vector3dAnimation
Animates changes in QVector3d values


//Behavior默认行为
 Rectangle {
      width: 75; height: 75; radius: width
      id: ball
      color: "salmon"

      Behavior on x {
          NumberAnimation {
              id: bouncebehavior
              easing {
                  type: Easing.OutElastic
                  amplitude: 1.0
                  period: 0.5
              }
          }
      }
      Behavior on y {
          animation: bouncebehavior
      }
      Behavior {
          ColorAnimation { target: ball; duration: 100 }
      }
  }

//动画序列
MouseArea {
          anchors.fill: parent
          onPressed: playbanner.start()
      }

      SequentialAnimation {
          id: playbanner
          running: false
          NumberAnimation { target: code; property: "opacity"; to: 1.0; duration: 200}
          NumberAnimation { target: create; property: "opacity"; to: 1.0; duration: 200}
          NumberAnimation { target: deploy; property: "opacity"; to: 1.0; duration: 200}
      }

所有的动画类型都继承自动画类型。不可能创建动画对象;相反,这个类型提供了动画类型的基本属性和方法。
动画类型有start()、stop()、resume()、pause()、restart()和complete()——所有这些方法都控制动画的执行。
//共享动画实例

  Rectangle {
      // NOT SUPPORTED: this will not work correctly as both Behaviors
      // try to control a single animation instance
      NumberAnimation { id: anim; duration: 300; easing.type: Easing.InBack }
      Behavior on x { animation: anim }
      Behavior on y { animation: anim }
  }

过度

//Transition 

  Rectangle {
      id: rect
      width: 100; height: 100
      color: "red"

      MouseArea {
          id: mouseArea
          anchors.fill: parent
      }

      states: State {
          name: "moved"; when: mouseArea.pressed
          PropertyChanges { target: rect; x: 50; y: 50 }
      }

      transitions: Transition {
          NumberAnimation { properties: "x,y"; easing.type: Easing.InOutQuad }
      }
  }
 transitions: [
    Transition {
        from: "stop"; to: "go"
        PropertyAnimation { target: stopLight
                            properties: "color"; duration: 1000 }
    },
    Transition {
        from: "go"; to: "stop"
        PropertyAnimation { target: goLight
                            properties: "color"; duration: 1000 }
    } ]

布局

1. 定位器布局

Column  列
Row     行
Grid    网格

Flow 超出边界自动换行 行布局

spacing           控件间距
Transition        过度 状态改变时

附加对象 Positioner
index : int
isFirstItem : bool
isLastItem : bool 

Repeater //创建大量相似项目
Repeater {
                model: 3
                delegate: EquipmentOne {
                    deviceName: index
                    onClicked: HKCom.globalLoader.source = 'ElectronicMap1.qml'
                }
}

2 锚点布局

qt qml

anchors group
anchors.top : AnchorLine         //上
anchors.bottom : AnchorLine
anchors.left : AnchorLine
anchors.right : AnchorLine
anchors.horizontalCenter : AnchorLine
anchors.verticalCenter : AnchorLine
anchors.baseline : AnchorLine  
anchors.fill : Item           //填充整个对象
anchors.centerIn : Item       //中心点对其到对象中心点
anchors.margins : real        
anchors.topMargin : real
anchors.bottomMargin : real
anchors.leftMargin : real
anchors.rightMargin : real
anchors.horizontalCenterOffset : real
anchors.verticalCenterOffset : real
anchors.baselineOffset : real
anchors.alignWhenCentered : bool

alignwhencenter(默认为true)强制居中锚点对齐到整个像素;如果居中的项的宽度或高度为奇数,则该项将定位在整个像素上,而不是半像素上。这确保了项目是刷得干净利落。在有些情况下,这是不可取的,例如当旋转项目抖动可能是明显的中心是四舍五入。

3 QtQuick.Layouts

import QtQuick.Layouts 1.11


ColumnLayout   列布局
GridLayout     网格布局
RowLayout      行布局
StackLayout    栈布局


spacing         项目间隔
Layout.minimumWidth
Layout.minimumHeight
Layout.preferredWidth
Layout.preferredHeight
Layout.maximumWidth
Layout.maximumHeight
Layout.fillWidth
Layout.fillHeight
Layout.alignment
Layout.margins
Layout.leftMargin
Layout.rightMargin
Layout.topMargin
Layout.bottomMargin

 ColumnLayout{
      spacing: 2

      Rectangle {
          Layout.alignment: Qt.AlignCenter
          color: "red"
          Layout.preferredWidth: 40
          Layout.preferredHeight: 40
      }

      Rectangle {
          Layout.alignment: Qt.AlignRight
          color: "green"
          Layout.preferredWidth: 40
          Layout.preferredHeight: 70
      }

      Rectangle {
          Layout.alignment: Qt.AlignBottom
          Layout.fillHeight: true
          color: "blue"
          Layout.preferredWidth: 70
          Layout.preferredHeight: 40
      }
  } 


GridLayout {
      id: grid
      columns: 3

      Text { text: "Three"; font.bold: true; }
      Text { text: "words"; color: "red" }
      Text { text: "in"; font.underline: true }
      Text { text: "a"; font.pixelSize: 20 }
      Text { text: "row"; font.strikeout: true }
  }
Layout.row
Layout.column
Layout.rowSpan
Layout.columnSpan

StackLayout {
      id: layout
      anchors.fill: parent
      currentIndex: 1
      Rectangle {
          color: 'teal'
          implicitWidth: 200
          implicitHeight: 200
      }
      Rectangle {
          color: 'plum'
          implicitWidth: 300
          implicitHeight: 200
      }
  }

模型视图

简介

qt qml

model        存储数据
view         展示收据
delegate     指定数据如何显示


view有
ListView
GridView
PathView

model
ListModel {
      id: nameModel
      ListElement { name: "Alice" }
      ListElement { name: "Bob" }
      ListElement { name: "Jane" }
      ListElement { name: "Harry" }
      ListElement { name: "Wendy" }
  }

  XmlListModel {
       id: feedModel
       source: "http://rss.news.yahoo.com/rss/oceania"
       query: "/rss/channel/item"
       XmlRole { name: "title"; query: "title/string()" }
       XmlRole { name: "link"; query: "link/string()" }
       XmlRole { name: "description"; query: "description/string()" }
  }
ObjectModel {
          id: itemModel
          Rectangle { height: 30; width: 80; color: "red" }
          Rectangle { height: 30; width: 80; color: "green" }
          Rectangle { height: 30; width: 80; color: "blue" }
      }

ListView

ListView {
            anchors.fill: parent
            model: ListModel { id: page_listmodel }

            delegate: ItemDelegate {
                id: control
                property var pageHandle
                width: parent.width
                height: 40
                highlighted: ListView.isCurrentItem
                text: page_name

                onClicked: {
                    ListView.view.currentIndex = index
                }
}

pathview shape path

qt qml


  import QtQuick 2.0

  Rectangle {
      width: 240; height: 200

      Component {
          id: delegate
          Item {
              width: 80; height: 80
              scale: PathView.iconScale
              opacity: PathView.iconOpacity
              Column {
                  Image { anchors.horizontalCenter: nameText.horizontalCenter; width: 64; height: 64; source: icon }
                  Text { id: nameText; text: name; font.pointSize: 16 }
              }
          }
      }

      PathView {
          anchors.fill: parent
          model: ContactModel {}
          delegate: delegate
          path: Path {
              startX: 120; startY: 100
              PathAttribute { name: "iconScale"; value: 1.0 }
              PathAttribute { name: "iconOpacity"; value: 1.0 }
              PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
              PathAttribute { name: "iconScale"; value: 0.3 }
              PathAttribute { name: "iconOpacity"; value: 0.5 }
              PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
          }
      }
  }
Shape {
         anchors.fill: parent
         ShapePath {
             strokeWidth: 1
             strokeColor: "#5fE9F0"
             fillColor: 'transparent'

             startX: 0; startY: 40
             PathLine { x: 0; y: chartView.height }
             PathLine { x: chartView.width; y: chartView.height }
             PathLine { x: chartView.width; y: 40 }
             PathLine { x: chartView.width / 3; y: 40 }
             PathLine { x: chartView.width / 3 - 25; y: 0 }
             PathLine { x: 25; y: 0 }
             PathLine { x: 0; y: 40 }
         }
     }

Canvs

渲染目标和渲染策略

renderTarget : enumeration

Canvas.Image              渲染目标 Image
Canvas.FramebufferObject - render to an OpenGL frame buffer

renderStrategy : enumeration

Canvas.Immediate    立刻执行
Canvas.Threaded     私有线程执行
Canvas.Cooperative  应用程序渲染线程执行

绘制操作Context2D

Canvas {
    id:canvas
    onPaint:{
       var ctx = canvas.getContext('2d');
       //...
    }
  }

requestPaint()  //请求绘制

fillStyle    填充颜色
strokeStyle  描边颜色

Pattern      纹理
创建单色纹理
variant createPattern(color color, enumeration patternMode)

Qt.SolidPattern
Qt.Dense1Pattern
Qt.Dense2Pattern
Qt.Dense3Pattern
Qt.Dense4Pattern
Qt.Dense5Pattern
Qt.Dense6Pattern
Qt.Dense7Pattern
Qt.HorPattern
Qt.VerPattern
Qt.CrossPattern
Qt.BDiagPattern
Qt.FDiagPattern
Qt.DiagCrossPattern

lineWidth   边线宽度
lineJoin    
lineCap

globalAlpha 全局 透明度  0.0 - 1.0

//矩形
fillRect      填充
strokeRect    描边

fillStyle = ctx.createPattern('red', Qt.DenselPattern)  //纹理填充

//状态保存和恢复
ctx.save()
ctx.restore()

//文本
fillText     实心
storekRect   空心

ctx.font = 'bold 50px Arial'

//路径绘制
ctx.beginPath()
ctx.closePath()

ctx.rect(x, y, width, height)
ctx.stroke()
注意每次新绘制时最好调用  ctx.beginPath()

moveTo()  移动
lineTo()  绘制直线
arc(x, y ,radius, startAngle, endAngle, anticlockwise)  x, y是中心点
arcTo()
ellipse(x, y, w, h) 椭圆
rounderRect
text

//渐变
var linear = ctx.createLinearGradient(10, 10, 100, 100)
linear.addColorStop(0, 'white')
ctx.fillStyle = line

//辐射渐变
object createRadialGradient(real x0, real y0, real r0, real x1, real y1, real r1)
//锥形渐变
object createConicalGradient(real x, real y, real angle)

//阴影
ctx.shadowBlur = 20       阴影宽度
ctx.shadowColor= 'blue'   阴影颜色
ctx.shadowOffsetX = 10        X方向偏移
ctx.shadowOffsetY = 10        Y方向偏移

//图片
canvas.loadImage(url)

onImageLoaded: {
    var ctx = getContext('2d')
    ctx.drawImage(url)
    canvas.requesPaint()
}

ctx.getImageData()  //获取绘图数据
ctx.putImageData()  //用数据绘图

//坐标转换
ctx.translate(x, y) 平移
ctx.scale(x, y)
ctx.rotate(Math.PI / 4)  旋转角度
ctx.shear(x, y)          扭曲
  





图形效果 import QtGraphicalEffects 1.12

Blend

使用混合模式合并两个源项
 

qt qml


cached : bool              
foregroundSource : variant 前景对象
mode : string     此属性定义当foregroundSource混合在source上时使用的模式。值不区分大小写
source : variant           原对象 



Item {
      width: 300
      height: 300

      Image {
          id: bug
          source: "images/bug.jpg"
          sourceSize: Qt.size(parent.width, parent.height)
          smooth: true
          visible: false
      }

      Image {
          id: butterfly
          source: "images/butterfly.png"
          sourceSize: Qt.size(parent.width, parent.height)
          smooth: true
          visible: false
      }

      Blend {
          anchors.fill: bug
          source: bug
          foregroundSource: butterfly
          mode: "subtract"
      }
  }

颜色

  • BrightnessContrast  亮度对比度
  • ColorOverlay             颜色叠加
  • Colorize                     着色使用 色调、亮度、饱和度
  • Desaturate                 饱和度
  • GammaAdjust           伽马调整
  • HueSaturation           色相饱和度 使用 色调、亮度、饱和度和原对象的相加
  • LevelAdjust               色阶调整

渐变效果

ConicalGradient 锥形渐变

angle : real                定义渐变的开始角度
cached : bool 
gradient : Gradient         
horizontalOffset : real      水平偏移
source : variant
verticalOffset : real        垂直偏移

ConicalGradient {
          anchors.fill: parent
          angle: 0.0
          gradient: Gradient {
              GradientStop { position: 0.0; color: "white" }
              GradientStop { position: 1.0; color: "black" }
          }
      }

LinearGradient 线性渐变 

cached : bool
end : variant         结束点位置
gradient : Gradient
source : variant
start : variant       开始点位置

LinearGradient {
          anchors.fill: parent
          start: Qt.point(0, 0)
          end: Qt.point(0, 300)
          gradient: Gradient {
              GradientStop { position: 0.0; color: "white" }
              GradientStop { position: 1.0; color: "black" }
          }
      }

RadialGradient 辐射渐变

angle : real                渐变旋转角度
cached : bool
gradient : Gradient平
horizontalOffset : real     水平偏移
horizontalRadius : real     水平半径
source : variant
verticalOffset : real       垂直偏移
verticalRadius : real       垂直半径

Item {
      width: 300
      height: 300

      RadialGradient {
          anchors.fill: parent
          gradient: Gradient {
              GradientStop { position: 0.0; color: "white" }
              GradientStop { position: 0.5; color: "black" }
          }
      }
  }

Displace

根据给定的位移映射移动源项的像素

qt qml

DropShadow 投影

cached : alias
color : alias             投影颜色
horizontalOffset : real   偏移
radius : int              模糊度
samples : alias           采样率  0 - 32默认 0 理想为 samples = 1 + radius * 2
source : alias      
spread : alias            边界多大区域被投影颜色加强 0.0 1.0
transparentBorder : alias 定义为true会使边框模糊显示
verticalOffset : real 

Item {
      width: 300
      height: 300

      Rectangle {
          anchors.fill: parent
      }

      Image {
          id: butterfly
          source: "images/butterfly.png"
          sourceSize: Qt.size(parent.width, parent.height)
          smooth: true
          visible: false
      }

      DropShadow {
          anchors.fill: butterfly
          horizontalOffset: 3
          verticalOffset: 3
          radius: 8.0
          samples: 17
          color: "#80000000"
          source: butterfly
      }
  }

InnerShadow 内阴影

cached : alias
color : alias             投影颜色
horizontalOffset : real   偏移
radius : int              模糊度
samples : alias           采样率  0 - 32默认 0 理想为 samples = 1 + radius * 2
source : alias      
spread : alias            边界多大区域被投影颜色加强 0.0 1.0
transparentBorder : alias 定义为true会使边框模糊显示
verticalOffset : real 
Item {
      width: 300
      height: 300

      Rectangle {
          anchors.fill: parent
      }

      Image {
          id: butterfly
          source: "images/butterfly.png"
          sourceSize: Qt.size(parent.width, parent.height)
          smooth: true
          visible: false
      }

      InnerShadow {
          anchors.fill: butterfly
          radius: 8.0
          samples: 16
          horizontalOffset: -3
          verticalOffset: 3
          color: "#b0000000"
          source: butterfly
      }
  }

模糊效果

  • FastBlur            快速模糊
  • GaussianBlur   高质量模糊
  • MaskedBlur      遮罩模糊
  • RecursiveBlur  递归模糊
  • DirectionalBlur 方向模糊
  • RadialBlur         径向模糊
  • ZoomBlur         缩放模糊
     

Glow 发光

cached : alias
color : alias
radius : alias      模糊度
samples : alias     采样率
source : alias
spread : alias     边界多大区域被投影颜色加强 0.0 1.0
transparentBorder : alias  边框模糊

 Item {
      width: 300
      height: 300

      Rectangle {
          anchors.fill: parent
          color: "black"
      }

      Image {
          id: butterfly
          source: "images/butterfly.png"
          sourceSize: Qt.size(parent.width, parent.height)
          smooth: true
          visible: false
      }

      Glow {
          anchors.fill: butterfly
          radius: 8
          samples: 17
          color: "white"
          source: butterfly
      }
  }

RectangularGlow 矩形发光 

cached : bool
color : color
cornerRadius : real   发光的外区圆角
glowRadius : real     此属性定义发光可到达项目区域之外的多少像素。
spread : real         发光强度
Item {
      width: 300
      height: 300

      Rectangle {
          id: background
          anchors.fill: parent
          color: "black"
      }

      RectangularGlow {
          id: effect
          anchors.fill: rect
          glowRadius: 10
          spread: 0.2
          color: "white"
          cornerRadius: rect.radius + glowRadius
      }

      Rectangle {
          id: rect
          color: "black"
          anchors.centerIn: parent
          width: Math.round(parent.width / 1.5)
          height: Math.round(parent.height / 2)
          radius: 25
      }
  }

遮罩

OpacityMask 不透明遮罩

qt qml

ThresholdMask 阈值遮罩

qt qml

QtQuick.Controls介绍

Style

1.配置问文件风格
qtquickcontrols2.conf文件

  [Controls]
  Style=Material

  [Universal]
  Theme=System
  Accent=Red

  [Material]
  Theme=Light
  Accent=Teal
  Primary=BlueGrey
2 c++设置
QQuickStyle::setStyle("Material");

3 文件选择
/main.qml
/CustomButton.qml
/+material/CustomButton.qml
如果  style设置为 material
引用的button就是 /+material/CustomButton.qml

平台部署

resources.qrc
main.qml
+windows/MyPage.qml
+windows/qtquickcontrols2.conf
+android/MyPage.qml
+android/qtquickcontrols2.conf

会自动选择平台相应文件

Control(基础类)

属性
availableHeight : real    //除去padding contentItem 高度
availableWidth : real     //除去padding contentItem 宽度
background : Item         //背景色 通常 Rectangle {}
bottomInset : real        //背景到边缘的间距
bottomPadding : real      //contentItem 到边缘的间距
contentItem : Item
focusPolicy : enumeration
focusReason : enumeration
font : font
horizontalPadding : real
hoverEnabled : bool       //接收鼠标移动事件
hovered : bool
implicitBackgroundHeight : real //background ? background.implicitWidth : 0.
implicitBackgroundWidth : real
implicitContentHeight : real  //contentItem ? contentItem.implicitHeight : 0
implicitContentWidth : real
leftInset : real
leftPadding : real
locale : Locale
mirrored : bool   //颠倒
padding : real 
palette : palette //
rightInset : real
rightPadding : real
spacing : real
topInset : real
topPadding : real
verticalPadding : real
visualFocus : bool   //通过键盘获取焦点 tab 快捷键等
wheelEnabled : bool  //启用键盘事件

qt qml

常用组件  

Button

qt qml

CheckBox

qt qml

DelayButton  延时触发按钮防止误触发

qt qml

RadioButton

qt qml

RoundButton

qt qml

Switch

qt qml

ToolButton   可配合ToolBar使用

qt qml

ApplicationWindow

ApplicationWindow创建应用程序的根窗口,使向该窗口添加可选的页眉和页脚变得很容易。

qt qml
Container 所有容器类的基类
Frame

用于在可视框架内将一组逻辑控件布局在一起

qt qml
GroupBox

GroupBox用于在有标题的可视框架中一起布局一组逻辑控件。

qt qml
Page

Page提供特定于页面的页眉和页脚项。使用ApplicationWindow设置页眉和页脚是完全可能的,但是如果页眉和页脚在每个屏幕上是不同的,那么最好使用Page。

qt qml
Pane

窗格提供与应用程序样式和主题匹配的背景颜色。窗格不提供自己的布局,但要求您定位其内容,例如使用RowLayout或ColumnLayout.

qt qml
ScrollView

ScrollView为用户定义的内容提供滚动

qt qml
StackView

StackView使用“后进先出”原则将内容页面组织成一个堆栈:最后一个要“推”到堆栈上的项是第一个要删除的项,最上面的项总是可见的项。

qt qml
SwipeView

SwipeView将内容页面组织成可滑动条

qt qml
TabBar

选项卡将内容页组织成选项卡

qt qml
TabButton

qt qml

ToolBar

工具栏是应用程序级和上下文敏感的操作和控件的容器。

qt qml

CheckDelegate

ItemDelegate提供了一个可检查的控件,用户可以按下并单击它, 像Button一样

qt qml
RadioDelegate

选择控件可以选中和不选中,一般使用从一系列选项中选择

qt qml
SwipeDelegate

可以左右滑动 显示更多信息

qt qml
SwitchDelegate

SwitchDelegate提供一个可切换的委托,它可以被打开或关闭。

qt qml

BusyIndicator

BusyIndicator可用于显示操作正在进行中,而UI必须等待操作完成

qt qml
PageIndicator

PageIndicator用于指示包含多个页面的容器中当前活动的页面。

qt qml
ProgressBar

qt qml
ScrollBar

滚动条是指示当前滚动位置的交互式条,可用于滚动到Flickable的特定位置

qt qml
ScrollIndicator

ScrollIndicator是一个非交互式指示器,指示当前滚动位置,可用于滚动到Flickable烁的特定位置。
qt qml

ComboBox

qt qml
Dial

Dial与传统的拨号盘类似,通常安装在音响或工业设备上

qt qml
RangeSlider

RangeSlider用于选择由两个值指定的范围,方法是将每个句柄沿轨道滑动

qt qml
Slider

滑块用于通过沿轨道滑动手柄来选择一个值

qt qml
TextArea  多行文本编辑器

TextField  单行文本编辑器

Tumbler

一个可旋转的轮子的项目,可以选择

qt qml

Menu

qt qml
MenuBar

qt qml
MenuBarItem 菜单栏选项

MenuItem       菜单项

Drawer         侧板,可以打开和关闭使用一个滑动手势

qt qml
Dialog

带有标准按钮和标题的弹出对话框,用于与用户进行短期交互

Popup

弹出式显示在其他应用程序内容之上。它提示用户做出决定或输入信息

qt qml
ToolTip

工具提示显示一小段通知用户控件功能的文本。它通常位于父控件之上或之下。

qt qml

MenuSeparator

将菜单中的一组项与相邻的项分开

qt qml
ToolSeparator

将工具栏中的一组项与相邻的项分隔开

qt qml

SpinBox

SpinBox允许用户通过单击向上或向下指示符按钮,或按键盘上的向上或向下来选择整数值。可选地,也可以使SpinBox成为可编辑的,这样用户可以在输入字段中输入文本值

qt qml

Action

Action表示一个抽象的用户界面动作,它可以有快捷方式,可以分配给菜单项和工具栏按钮。

ToolButton {
      id: toolButton
      action: copyAction
  }
 MenuItem {
      id: menuItem
      action: copyAction
      text: qsTr("&Copy selected Text")
  }

Label 

Label通过样式和字体继承扩展了文本。默认的颜色和字体是特定于样式的。标签也可以有一个视觉背景项

SplitView  (Control 1)

SplitView是一个控件,它水平或垂直地放置项目,每个项目之间有一个可拖动的拆分器

qt qml

TabView Tab Control 1

qt qml

 TabView {
      Tab {
          title: "Red"
          Rectangle { color: "red" }
      }
      Tab {
          title: "Blue"
          Rectangle { color: "blue" }
      }
      Tab {
          title: "Green"
          Rectangle { color: "green" }
      }
  }

Qt Labs Platform

  • ColorDialog,
  • FileDialog,
  • FolderDialog,
  • FontDialog,
  • MessageDialog

Picture  (Qt Quick Extras)

图片以可伸缩的矢量格式显示图标。它还可以通过color属性为图标着色。

CircularGauge(Qt Quick Extras)

该仪器与传统的机械式仪表类似,使用指针显示来自某些输入的数值,如车辆的速度或气压,

qt qml

Gauge (Qt Quick Extras)

仪表控件沿水平或垂直轴显示某个范围内的值。它可以被看作是ProgressBar的扩展,提供标记和标签来提供进度的可视化度量。

qt qml

PieMenu(Qt Quick Extras)

PieMenu提供了一个径向上下文菜单作为传统菜单的替代。PieMenu中的所有项都与控件中心的距离相等

qt qml

Thmbler ThmblerColumn

qt qml

ActionGroup

ButtonGroup

StandardPaths  (Qt Labs Platform)

StandardPaths单例类型提供了查询标准系统路径的方法。标准路径通常与文件对话框和文件夹对话框类型结合使用。

 FileDialog {
      folder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation)
  }

SystemTrayIcon (Qt Labs Platform)

 SystemTrayIcon {
      visible: true
      icon.source: "qrc:/images/tray-icon.png"

      onActivated: {
          window.show()
          window.raise()
          window.requestActivate()
      }
  }

 SystemTrayIcon {
      visible: true
      icon.source: "qrc:/images/tray-icon.png"

      menu: Menu {
          MenuItem {
              text: qsTr("Quit")
              onTriggered: Qt.quit()
          }
      }
  }
 SystemTrayIcon {
      visible: true
      icon.source: "qrc:/images/tray-icon.png"

      onMessageClicked: console.log("Message clicked")
      Component.onCompleted: showMessage("Message title", "Something important came up. Click this to know more.")
  }
 

控件使用

ToolButton

ToolButton {
    autoExclusive : true  //互斥访问 同一父类
}

ToolButton {
    spacing: 10
    display: AbstractButton.TextBesideIcon
    text: '返回'
    font.pixelSize: 16
    icon {
          source: 'qrc:/image/return.png'
           color: 'transparent'
    }
    Component.onCompleted: {contentItem.color = '#5282F0'}  //修改字体颜色
    onClicked: {}
}


flat : bool        //没有背景色
highlighted : bool //高亮显示背景色

弹窗Popup

Popup {
        id: popup
        anchors.centerIn: Overlay.overlay
        width: 400
        height: 400
        modal: true
        focus: true
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutsideParent
        Label {
            text: "popou"
        }
    }

ScrollView 滚动视图

 ScrollView {
      width: 200
      height: 200
      clip: true

      Label {
          text: "ABC"
          font.pixelSize: 224
      }
  }


如果一个子项 可以根据隐含大小计算 如果多个子类  必须指定 contentWidth contentHeight


  ScrollView {
      id: control

      width: 200
      height: 200
      focus: true

      Label {
          text: "ABC"
          font.pixelSize: 224
      }

      ScrollBar.vertical: ScrollBar {
          parent: control
          x: control.mirrored ? 0 : control.width - width
          y: control.topPadding
          height: control.availableHeight
          active: control.ScrollBar.horizontal.active
      }

      ScrollBar.horizontal: ScrollBar {
          parent: control
          x: control.leftPadding
          y: control.height - height
          width: control.availableWidth
          active: control.ScrollBar.vertical.active
      }

      background: Rectangle {
          border.color: control.activeFocus ? "#21be2b" : "#bdbebf"
      }
  }

ScrollBar 滚动条

滚动条是一个可用于滚动到特定位置的交互式栏。

active : bool
horizontal : bool
interactive : bool
minimumSize : real
orientation : enumeration
policy : enumeration
position : real
pressed : bool
size : real
snapMode : enumeration
stepSize : real
vertical : bool
visualPosition : real
visualSize : real 

附加属性

horizontal : ScrollBar
vertical : ScrollBar 

函数

void decrease()  减小位置
void increase()  增大位置

//指定父类 来自动管理, 这可能很有用,例如,如果滚动条应该放置在可闪烁的裁剪之外
 Flickable {
      id: flickable
      clip: true
      // ...
      ScrollBar.vertical: ScrollBar {
          parent: flickable.parent
          anchors.top: flickable.top
          anchors.left: flickable.right
          anchors.bottom: flickable.bottom
      }
  }

//不能监听附加对象 事件 
Flickable {
      focus: true

      Keys.onUpPressed: scrollBar.decrease()
      Keys.onDownPressed: scrollBar.increase()

      ScrollBar.vertical: ScrollBar { id: scrollBar }
  }

ScrollIndicator非交互式指示器 指示当前滚动位置

用法和ScrollView相同

active : bool
horizontal : bool
minimumSize : real        //指示器最小大小
orientation : enumeration
position : real
size : real
vertical : bool
visualPosition : real
visualSize : real 
附加属性
horizontal : ScrollIndicator
vertical : ScrollIndicator 

Map地图

Place  保存位置信息  和 显示信息还有显示图片等信息
Map    显示地图
Route  导航

每个实例需要后台插件来提供数据

Plugin {
    name:""指定插件
    PluginParameter { name: "osm.mapping.highdpi_tiles"; value: true } //高清显示title
}
//可用插件 name  具体查看插件 详细信息  
osm  提供地图
Esri
HERE
itemsoverlay
mapboxgl
mapbox

//Map 可以添加控件

MapCircle
MapRectangle
MapPolygon
MapPolyline
MapQuickItem

//GeocodeModel 
地址到坐标查询 / 坐标到地址查询

Address - Geocoding (address to coordinate)
coordinate - Reverse geocoding (coordinate to address)
string - Geocoding (address to coordinate)


//Route 导航

Route
RouteSegment
RouteManeuver
RouteModel

//搜索
 PlaceSearchModel {
      id: searchModel

      plugin: myPlugin
      searchTerm: "pizza"
      searchArea: QtPositioning.circle(startCoordinate);

      Component.onCompleted: update()
 }
 Map {
      id: map
      anchors.fill: parent
      plugin: myPlugin;
      center: locationOslo
      zoomLevel: 13

      MapItemView {
          model: searchModel
          delegate: MapQuickItem {
              coordinate: place.location.coordinate

              anchorPoint.x: image.width * 0.5
              anchorPoint.y: image.height

              sourceItem: Column {
                  Image { id: image; source: "marker.png" }
                  Text { text: title; font.bold: true }
              }
          }
      }
  }


//! 自定义地图背景
1. 
plugin: Plugin {
        name: "mapboxgl"
        PluginParameter {
            name: "mapboxgl.mapping.additional_style_urls"
            value: "qrc:/image/MapboxStyle.json"
        }
    }
2.创建
mapboxstyle.json

{
    "version": 8,
    "name": "overlayimage",
    "sprite": "mapbox://styles/mapbox/dark-v9",
    "glyphs": "mapbox://fonts/tmpsantos/{fontstack}/{range}.pbf",
    "sources": {
        "overlay": {
            "type": "image",
            "url": "qrc:/images/resource/image/mapMarker/mine.png",
            "coordinates": [
                [110.286407114808, 39.863747068868],
                [110.299161991398, 39.863747068868],
                [110.299161991398, 39.854218133828],
                [110.286407114808, 39.854218133828]
            ]
        }
    },
    "layers": [
        {
            "id": "background",
            "type": "background",
            "paint": {
                "background-color": "rgb(4,7,14)"
            },
            "interactive": true
        },
        {
            "id": "overlay",
            "source": "overlay",
            "type": "raster",
            "paint": { "raster-opacity": 0.6 }
        }
    ],
    "draft": true,
    "id": "cjb1kxpcabzjb2rr0mltlvp0i",
    "modified": "2017-12-11T02:29:15.055Z",
    "owner": "scfjp",
    "visibility": "private",
    "created": "2017-12-11T02:29:15.055Z"
}


#wmts
{
    "version": 8,
    "name": "overlayimage",

    "sources": {
        "overlay": {
            "type": "raster",
            "tiles": ["http://117.160.210.2:33114/geoserver/gwc/service/wmts?layer=XiongAn:result&style=&tilematrixset=EPSG:3857&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix=EPSG:3857:{z}&TileCol={x}&TileRow={y}"]

        }
    },
    "layers": [
        {
            "id": "overlay",
            "source": "overlay",
            "type": "raster"
        }
    ],
    "light": {
      "anchor": "viewport",
      "color": "white",
      "intensity": 1
    }
}

多媒体播放

Audio
Camera
CameraCapture
CameraExposure
CameraFlash
CameraFocus
CameraImageProcessing
CameraRecorder
MediaPlayer
Playlist
PlaylistItem
QtMultimedia
Radio
RadioData
SoundEffect
Torch
Video
VideoOutput

//音频
 Text {
      text: "Click Me!";
      font.pointSize: 24;
      width: 150; height: 50;

      Audio {
          id: playMusic
          source: "music.wav"
      }
      MouseArea {
          id: playArea
          anchors.fill: parent
          onPressed:  { playMusic.play() }
      }
  }
//视频

 Video {
      id: video
      width : 800
      height : 600
      source: "video.avi"

      MouseArea {
          anchors.fill: parent
          onClicked: {
              video.play()
          }
      }

      focus: true
      Keys.onSpacePressed: video.playbackState == MediaPlayer.PlayingState ? video.pause() : video.play()
      Keys.onLeftPressed: video.seek(video.position - 5000)
      Keys.onRightPressed: video.seek(video.position + 5000)
  }

Charts图表

简介 

qt qml

1. 工程添加
QT += charts
import QtCharts 2.3

修改为 QApplication 不然 QCharts报错

2 使用 
主要显示控件

ChartView {}

ChartView需要添加 AbstractSeries 的子类作为显示对象

//可用类型
LineSeries, AreaSeries, BarSeries, StackedBarSeries, PercentBarSeries, HorizontalBarSeries, HorizontalStackedBarSeries, HorizontalPercentBarSeries, PieSeries, ScatterSeries, SplineSeries, BoxPlotSeries, or CandlestickSeries.

//添加例子:
ChartView {
      width: 400
      height: 300
      theme: ChartView.ChartThemeBrownSand
      antialiasing: true

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

//轴线  坐标轴类型

Value axis          数值
Category axis       分类
Bar category axis   条形
Date-time axis      时间
Logarithmic value axis 对数

ValueAxis{
                      id:axia_y1
                      labelFormat: '%d RH%'
                      tickCount:10
                      labelsFont.pixelSize: 14
                      min: 0
                      max: 200
 }

一个char可以指定多个坐标  但是不能指定不同类型的坐标轴类型

Legned  
图例是显示图表图例的图形对象。当系列更改时,ChartView类型将更新图例状态。图例类型属性可以附加到ChartView类型。例如:

功能
1. 折线图和平滑曲线图

2. 面积图和散列图 

3. 条形图

4. 饼图

5. 盒须图

6. 烛台图
7. 极坐标图

折线图和平滑曲线图

ChartView {
      title: "Line"
      anchors.fill: parent
      antialiasing: true

      LineSeries {
          name: "LineSeries"
          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 }
      }
  }
ChartView {
      title: "Spline"
      anchors.fill: parent
      antialiasing: true

      SplineSeries {
          name: "SplineSeries"
          XYPoint { x: 0; y: 0.0 }
          XYPoint { x: 1.1; y: 3.2 }
          XYPoint { x: 1.9; y: 2.4 }
          XYPoint { x: 2.1; y: 2.1 }
          XYPoint { x: 2.9; y: 2.6 }
          XYPoint { x: 3.4; y: 2.3 }
          XYPoint { x: 4.1; y: 3.1 }
      }
  }

 面积图和散列图 

ChartView {
    id: chartView
    antialiasing: true

    animationOptions: ChartView.AllAnimations
    legend.alignment: Qt.AlignRight

    margins.top: 30

    legend.labelColor: 'white'
    backgroundColor: "transparent"

    CategoryAxis {
        id: monthAxis

        min: 1
        max: 12
        gridVisible: false
        color: '#52E9F0'
        labelsColor: '#A9EAED'
        labelsPosition: CategoryAxis.AxisLabelsPositionOnValue
        Component.onCompleted: {
            for(var month = 1; month <= 12; month++) {
                append(qsTr('%1月').arg(month), month)
            }
        }
    }

    ValueAxis {
        id: precentAxis
        gridVisible: false
        min: 0
        max: 50
        tickCount: 6

        labelFormat: "%d\%"
        color: '#52E9F0'
        labelsColor: '#A9EAED'
    }

    AreaSeries {
        name: "去年"
        axisX: monthAxis
        axisY: precentAxis

        upperSeries: LineSeries {
            XYPoint { x: 1; y: 13 }
            XYPoint { x: 2; y: 22 }
            XYPoint { x: 3; y: 14 }
            XYPoint { x: 4; y: 16 }
            XYPoint { x: 5; y: 17 }
            XYPoint { x: 6; y: 18 }
            XYPoint { x: 7; y: 34 }
            XYPoint { x: 8; y: 44 }
            XYPoint { x: 9; y: 23 }
            XYPoint { x: 10; y: 33 }
            XYPoint { x: 11; y: 22 }
            XYPoint { x: 12; y: 11 }
        }
    }
}

 条形图

ChartView {
    id: chartView
    antialiasing: true

    animationOptions: ChartView.AllAnimations
    legend.alignment: Qt.AlignRight
    margins.top: 30

    legend.labelColor: 'white'
    backgroundColor: "transparent"

    ValueAxis {
        id: precentAxis
        gridVisible: false

        labelFormat: "%d"
        color: '#52E9F0'
        labelsColor: '#A9EAED'
    }

    BarSeries {
        id: mySeries
        labelsVisible: true

        labelsPosition: AbstractBarSeries.LabelsOutsideEnd

        axisX: BarCategoryAxis {

            gridVisible: false
            color: '#52E9F0'
            labelsColor: '#A9EAED'
            categories: ['扶梯', '直梯' ]
        }
        axisY: precentAxis
        MBarSet { label: "关闭"; values: [255, 113]}
        MBarSet { label: "开启"; values: [236, 14]   }
        MBarSet { label: "故障"; values: [2317, 25]  }
    }
}

饼图

ChartView {
    id: chartView
    antialiasing: true

    animationOptions: ChartView.AllAnimations
    legend.alignment: Qt.AlignRight

    margins.top: 40
    margins.bottom: 0
    margins.left: 0
    margins.right: 0

    legend.labelColor: 'white'
    backgroundColor: "transparent"

    PieSeries {
        id: pie
        holeSize: 0.6
        size: 0.8

        PieSlice {
            label: "故障设备";
            value: 13.5
            labelColor: 'white'
            labelVisible: true;

        }
        PieSlice {
            label: "开启设备"; value: 10.9;
            labelColor: 'white'
            labelVisible: true;
        }
        PieSlice {
            label: "关闭设备"; value: 8.6;
            labelColor: 'white'
            labelVisible: true;
        }
    }
}

webview

//工程文件添加代码
QT += qml quick webview

//在 main.cpp中添加代码

QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
QGuiApplication app(argc, argv);
QtWebView::initialize();
//使用
import QtWebView 1.13
WebView {
        anchors.fill: parent
        url: 'qrc:/baidu.html'
}

常用功能

实现移动
Label {

    text: qsTr("你好")
    MouseArea {
        anchors.fill: parent;
        drag.target: parent;  //添加这句实现移动
    }
}

杂项

资源文件读取

qml.qrc资源文件使用,
QUrl("qrc:/qml/qml/main.qml")   QUrl要带qrc
QFile(":/img/1.text")           string 不用带qrc
以.qml和.js结尾的文件            再外部调用c++读取不出文件内容        

刷新界面闪烁

//界面启动闪烁
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);  //设置opengl加载方式

不能执行eval()

qml javascript执行eval()报错  解决:再封装一层函数 function g_eval() {return eval();}

XMLHttpRequest();使用https 

XMLHttpRequest();使用https
var xhr = new XMLHttpRequest();使用https
报错:QSslSocket::connectToHostEncrypted: TLS initialization failed
解决:libeay32.dll和ssleay32.dll跟QtNetwork.dll放在同一目录下,程序发布时要拷贝到跟目录

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/11056.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信