qt qml

前言

本文作爲開發QT qml 技術總結和常用函數功能總結,不是很適合初學者。

初學者參考資源:https://pan.baidu.com/s/1rwOwKOMoON0ffGcSorndew  本人收集的資料僅供參考。

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 錨點佈局

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
      }
  }

模型視圖

簡介

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


  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

使用混合模式合併兩個源項
 


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

根據給定的位移映射移動源項的像素

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 不透明遮罩

ThresholdMask 閾值遮罩

 

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  //啓用鍵盤事件

常用組件  

Button

CheckBox

DelayButton  延時觸發按鈕防止誤觸發

RadioButton

RoundButton

Switch

ToolButton   可配合ToolBar使用


ApplicationWindow

ApplicationWindow創建應用程序的根窗口,使向該窗口添加可選的頁眉和頁腳變得很容易。


Container 所有容器類的基類
Frame

用於在可視框架內將一組邏輯控件佈局在一起


GroupBox

GroupBox用於在有標題的可視框架中一起佈局一組邏輯控件。


Page

Page提供特定於頁面的頁眉和頁腳項。使用ApplicationWindow設置頁眉和頁腳是完全可能的,但是如果頁眉和頁腳在每個屏幕上是不同的,那麼最好使用Page。


Pane

窗格提供與應用程序樣式和主題匹配的背景顏色。窗格不提供自己的佈局,但要求您定位其內容,例如使用RowLayout或ColumnLayout.


ScrollView

ScrollView爲用戶定義的內容提供滾動


StackView

StackView使用“後進先出”原則將內容頁面組織成一個堆棧:最後一個要“推”到堆棧上的項是第一個要刪除的項,最上面的項總是可見的項。


SwipeView

SwipeView將內容頁面組織成可滑動條


TabBar

選項卡將內容頁組織成選項卡


TabButton

ToolBar

工具欄是應用程序級和上下文敏感的操作和控件的容器。


CheckDelegate

ItemDelegate提供了一個可檢查的控件,用戶可以按下並單擊它, 像Button一樣


RadioDelegate

選擇控件可以選中和不選中,一般使用從一系列選項中選擇


SwipeDelegate

可以左右滑動 顯示更多信息


SwitchDelegate

SwitchDelegate提供一個可切換的委託,它可以被打開或關閉。


BusyIndicator

BusyIndicator可用於顯示操作正在進行中,而UI必須等待操作完成


PageIndicator

PageIndicator用於指示包含多個頁面的容器中當前活動的頁面。


ProgressBar


ScrollBar

滾動條是指示當前滾動位置的交互式條,可用於滾動到Flickable的特定位置


ScrollIndicator

ScrollIndicator是一個非交互式指示器,指示當前滾動位置,可用於滾動到Flickable爍的特定位置。


ComboBox


Dial

Dial與傳統的撥號盤類似,通常安裝在音響或工業設備上


RangeSlider

RangeSlider用於選擇由兩個值指定的範圍,方法是將每個句柄沿軌道滑動


Slider

滑塊用於通過沿軌道滑動手柄來選擇一個值


TextArea  多行文本編輯器


TextField  單行文本編輯器


Tumbler


一個可旋轉的輪子的項目,可以選擇


Menu


MenuBar


MenuBarItem 菜單欄選項


MenuItem       菜單項


Drawer         側板,可以打開和關閉使用一個滑動手勢



Dialog


帶有標準按鈕和標題的彈出對話框,用於與用戶進行短期交互


Popup

彈出式顯示在其他應用程序內容之上。它提示用戶做出決定或輸入信息


ToolTip


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


MenuSeparator

將菜單中的一組項與相鄰的項分開


ToolSeparator


將工具欄中的一組項與相鄰的項分隔開

SpinBox

SpinBox允許用戶通過單擊向上或向下指示符按鈕,或按鍵盤上的向上或向下來選擇整數值。可選地,也可以使SpinBox成爲可編輯的,這樣用戶可以在輸入字段中輸入文本值

Action

Action表示一個抽象的用戶界面動作,它可以有快捷方式,可以分配給菜單項和工具欄按鈕。

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

Label 

Label通過樣式和字體繼承擴展了文本。默認的顏色和字體是特定於樣式的。標籤也可以有一個視覺背景項

SplitView  (Control 1)

SplitView是一個控件,它水平或垂直地放置項目,每個項目之間有一個可拖動的拆分器

TabView Tab Control 1

 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)

該儀器與傳統的機械式儀表類似,使用指針顯示來自某些輸入的數值,如車輛的速度或氣壓,

Gauge (Qt Quick Extras)

儀表控件沿水平或垂直軸顯示某個範圍內的值。它可以被看作是ProgressBar的擴展,提供標記和標籤來提供進度的可視化度量。

PieMenu(Qt Quick Extras)

PieMenu提供了一個徑向上下文菜單作爲傳統菜單的替代。PieMenu中的所有項都與控件中心的距離相等

Thmbler ThmblerColumn


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 }
              }
          }
      }
  }


多媒體播放

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圖表

簡介 

 

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放在同一目錄下,程序發佈時要拷貝到跟目錄

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章