2015-12-14 45 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“”。 –