1. 程式人生 > 實用技巧 >qt qml使用踩坑指南

qt qml使用踩坑指南

最近要用qt開發一個手機藍芽app,藍芽demo已經寫好(包含客戶端和服務端),過兩天整理下發上來.先把qml踩的坑記錄下

01  qml佈局,,,,最好使用動態佈局方式,頭尾可以使用固定的大小,中間可以使用比例,或者全部都可以使用比例進行設計,

   注意一點,anchors貌似不可以使用資料計算的方式,但是width和height可以  eg  height:(parent.height-rect1.height-rect6.height)*0.6

02  qml製作動態按鈕時候,每個按鈕之間最好使用column進行隔離,按鈕之間不要使用margin,,不然按鈕動態效果會影響其他的按鈕.動態按鈕的製作如下

import QtQuick 2.12
import QtQuick.Controls 2.12

Button {
    signal buttonClick()

    id: btnmousearea00
    width: 65
    height: 40
    background: Rectangle {
        id: btnmouseareabg0011
        radius: 3
        color: "#0066FF"
    }

    MouseArea {
        anchors.fill: parent
        onPressed: {
            btnmousearea00.width = btnmousearea00.width + 7
            btnmousearea00.height = btnmousearea00.height + 5
            btnmouseareabg0011.color = "#66FF00"
        }

        onReleased: {
            btnmousearea00.width = btnmousearea00.width - 7
            btnmousearea00.height = btnmousearea00.height - 5
            btnmouseareabg0011.color = "#0066FF"

        }

        onClicked: {
            buttonClick()
        }
    }
}

    按鈕之間的分割如下

import QtQuick 2.12
import QtQuick.Controls 2.12

Rectangle {

    property int btnwidth: 65

    width: parent.width
    //height: 48
    color: "lightgrey"


    Text {
        id: btnmiddle00
        anchors.centerIn: parent
    }


    Column{
        width: parent.width/3
        anchors.centerIn: parent
        MyButton {
            anchors.centerIn: parent

            text: "讀取"
    //                icon.name: "home"
    //                icon.color : "transparent"
    //                action: homeAction
            //font.pointSize: 16

            onClicked: console.log("123");
        }
    }

    Column{
        width: parent.width/3
        anchors.verticalCenter: btnmiddle00.verticalCenter
        anchors.right: btnmiddle00.left
        anchors.rightMargin: btnwidth/2
//        anchors.rightMargin: 10 + btnwidth/2
        MyButton {
            anchors.centerIn: parent
            text: "寫入"

            //onClicked: console.log()
        }
    }
    Column{
        width: parent.width/3
        anchors.verticalCenter: btnmiddle00.verticalCenter
        anchors.left: btnmiddle00.right
        anchors.leftMargin: btnwidth/2
        MyButton {
            anchors.centerIn: parent
            text: "初始值"
        }
    }
}

03  可以自己定義一些模組之間某些資訊可以使用變數傳遞進去,如下

04  一個非常奇葩的bug,氣的我都不想記下來,上圖的BoxRadoiBtn2有個//  anchors.fill:parent

   這句話看著沒問題,意思是繼承父類的全部空間,但是,在scrollview中就有大問題了,正常情況下,我的程式執行時這樣的(左邊)

  加上這一句之後,就變天了,程式就變成了這樣色兒的,這玩意兒給我頭疼的,整了,一下午時間就浪費在這破玩意兒上了,反反覆覆就是一句程式碼的事兒.  

    

05  使用rectangle做測試的時候,注意父子之間一定要看一看空間關係,rectangle大小最好指定好,,最好能帶上文字,因為文字一定程度上可以不受尺寸的約束