2015-12-14 42 views

回答

1

如果你想在QML中聲明一個「類」,你必須創建一個新的QML文件。它的名字必須以大寫字母開頭。你也可以使用C++創建自定義對象,但可能這不是你正在尋找的。

假設您要創建自定義Text元素,以便文本總是居中並適合給定尺寸。所以,你創建一個名爲CustomText.qml文件,並寫入:

/* CustomText.qml file */  

import QtQuick 2.0 

Text { 
    id: customText 
    horizontalAlignment: Text.AlignHCenter 
    verticalAlignment: Text.AlignVCenter 
    clip: true 
    fontSizeMode: Text.Fit 
    font.pixelSize: height 
    wrapMode: Text.WordWrap 
    minimumPixelSize: 3 
    color: "black" 

    /* using these lines you can set custom font loaded from a file */ 
// font.family: customFont.name 
// FontLoader { 
//  id: customFont 
//  source: "qrc:/myCustomFont.ttf" 
// } 
} 

現在你可以使用這樣的:

/* main.qml file */ 
import QtQuick 2.3 
import QtQuick.Window 2.2 

Window { 
    visible: true 

    width: 300 
    height: 300 

    Rectangle { 
     id: rectangle1 
     color: "lightgrey" 
     x: 5 
     y: 5 
     width: 200 
     height: 50 

     CustomText { 
      anchors.fill: parent 
      text: "testing custom text object" 
     } 
    } 

    Rectangle { 
     id: rectangle2 
     color: "lightgrey" 
     anchors.left: rectangle1.left 
     anchors.top: rectangle1.bottom 
     anchors.topMargin: 5 
     width: 50 
     height: 50 

     CustomText { 
      anchors.fill: parent 
      text: "testing custom text object" 
     } 
    } 

    Rectangle { 
     id: rectangle3 
     color: "lightgrey" 
     anchors.left: rectangle2.left 
     anchors.top: rectangle2.bottom 
     anchors.topMargin: 5 
     width: 100 
     height: 100 

     CustomText { 
      anchors.fill: parent 
      text: "testing custom text object" 
     } 
    } 
} 

這就是它會是什麼樣子:

image showing example code in action

+0

如果從現在開始,每個元素都必須使用綠色字體顏色。我必須爲每個元素創建一個自定義QML嗎?我想採取一個現有的項目,並以某種方式改變它的風格 –

+1

@DanielSantos不幸的是。您必須手動將每個「文本」更改爲「CustomText」,並在其中設置「color:」green「」。 –