Specifying font for many Text-elements in Qt QML(在 Qt QML 中为许多文本元素指定字体)
问题描述
我有一个通过 QML 文件指定的小部件.这个小部件包含一个顶级Rectangle,它包含两个Columns.这些 Columns 中的每一个都包含许多 Text 元素.这个 QML 小部件包含在 C++ 中 QDeclarativeView 的子类中.
I have a widget specified through a QML file. This widget contains a top levelRectangle which contains two Columns. Each of these Columns contains many Text-elements. This QML widget is wrapped in a subclass of QDeclarativeView in C++.
我想为每个 Text 元素指定字体.今天我通过指定顶级属性来做到这一点:
I want to specify the font for each of these Text-elements. Today I do this by specifying top-level properties:
property string fontfamily: "Arial"
property bool fontbold: false
property bool fontitalic: false
property int fontpixelsize: 11
property string fontcolor: "White"
并将每个 Text 元素绑定到这些属性:
and bind each Text-elements to these properties:
Text
{   
    color: fontcolor
    font.family: fontfamily
    font.bold: fontbold
    font.italic: fontitalic
    font.pixelSize: fontpixelsize
    ...
}
这不是很优雅,每次我需要支持新的东西时都需要添加新的字段(例如带下划线的字体).我无法声明 font 类型的属性并绑定到它(小部件为空白,qmlviewer 警告属性后的预期类型").
This isn't very elegant and new fields needs to be added every time I need support for something new (e.g. underlined fonts). I have not been able to declare a property of type font and bind to this instead (widget is blank and qmlviewer warns about "expected type after property").
是否有更好的方法为所有 Text 元素指定字体?
Is there a better way to specify a font for all Text-elements?
注意!我正在手写 QML 文件.
Note! I'm handwriting the QML files.
推荐答案
另一种可能是编写一个新的 QML 组件,它继承自 Text 并默认设置一些属性:
Another possibility is to write a new QML component, that inherits from Text an sets some properties by default:
StyledText.qml
import QtQuick 1.0
Text {
    // set default values
    color: "blue"
    font.family: "Arial"
    font.bold: true
    font.italic: true
    font.pixelSize: 12
}
main.qml
import QtQuick 1.0
Rectangle {
    Row {
        spacing: 10
        Column {
            StyledText {
                text: "Foo1"
            }
            StyledText {
                text: "Bar1"
            }
            StyledText {
                text: "Baz1"
            }
        }
        Column {
            StyledText {
                text: "Foo2"
            }
            StyledText {
                text: "Bar2"
            }
            StyledText {
                text: "Baz2"
            }
        }
    }
}
这篇关于在 Qt QML 中为许多文本元素指定字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Qt QML 中为许多文本元素指定字体
 
				
         
 
            
        基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				