Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c++ - Specifying font for many Text-elements in Qt QML

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++.

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"

and bind each Text-elements to these properties:

Text
{   
    color: fontcolor
    font.family: fontfamily
    font.bold: fontbold
    font.italic: fontitalic
    font.pixelSize: fontpixelsize
    ...
}

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").

Is there a better way to specify a font for all Text-elements?

Note! I'm handwriting the QML files.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Qt 5.6 (at least, probably earlier too), you can use Qt.font() to dynamically allocate a font object and refer to it elsewhere. So, this works:

property font myFont: Qt.font({
    family: fontfamily,
    bold: fontbold,
    italic: fontitalic,
    pixelSize: fontpixelsize
});

Text
{   
    color: fontcolor
    font: parent.myFont
}

More info on Qt.font() here: https://doc-snapshots.qt.io/qt5-5.6/qml-qtqml-qt.html#font-method


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...