QML Multi-line Texts Handling
English
[toc align_right="yes" depth="2"]
QML Multi-line Texts Handling
Introduction
There are many situations where we need to handle relatively lengthy fragments of text, for example in help systems. Qt framework has its "Assistance help system":http://developer.qt.nokia.com/doc/qt-4.8/assistant-manual.html implemented in Qt C+. As another example we may consider learning content for which we need a flexible interface to multi-line blocks of text.
Don't confuse this with text processing; we are considering options for easy structuring of text in blocks and their rendering through a flexible QML interface.
At first look, QML with its Text element, is oriented to handling short text portions like labels, titles, dialogs, etc. Combining rich text formatting options in QML with its software architecture possibilities we may have interesting solutions.
The starting point is the requirement to separate text blocks from basic QML code, encapsulating the text blocks in autonomous units, and providing a powerful interface. It is clear that a text block can change very often - editing of the text, translation in other languages and so on. The solution is to form a QML component and instantiate it in the basic application code in places where we need it.
h2. Text Component
Let us recall how we define a "component in QML":http://doc.qt.nokia.com/4.7/qdeclarativedocuments.html. The next snippet demonstrates our text component, which is used in all examples that follow. The text component is placed in a file named TextTemplate.qml. That is the name of our text component, which is used in main QML file. This name appears in next illustrating code fragments. You have needed explanations in comments.
TextTemplate.qml
//This file forms a text component to be included as template in other files<br />//Note that the name of the component file has to begin with a capital letter<br />//The component file is placed in the same directory as files, which will use it
<br />import QtQuick 1.0
<br />Item {id:container<br />//This Item is not needed really. The Text element could form the component<br />//directly. It is used to demonstrate how to get Text element properties at top<br />//level to be able to control them programmatically. You may need a container if you<br />//have two (or more) Text elements and/or combine a Text element with others element.<br /> width:500; height:500
<br />//Bind Text element properties with properties at top level<br /> property string wrap:"Text.WordWrap&quot;<br /> property real topwidth:300<br /> property string label:"Sample text&quot;<br /> property color paint
<br /> Text { id:template<br /> width:topwidth //Some properties of Text element take effect only<br /> //if width property is defined<br /> color:paint<br /> font.pointSize:12<br /> wrapMode:wrap //If the text line length exceeds the width property<br /> //value the text will be wrapped (on word boundaries)<br /> text:label //A text property value is anything that results in to a string<br /> }<br />}
h2. Text Component Handling
As a first solution (and trivial one) for text blocks structuring we may define as many components as many text blocks we have. In the application code we include components in places where we need to display respective text blocks.
The second approach uses the possibility to bind a value to a QML element property at a later time - not when the element is defined. And we want to do this programmatically. In our text component we bind text property to another top level property (note it is of type string). This way the text component becomes a generic entity where different text property values could be bound when the component is used in the basic QML code. In other words, we use the text component as a template, instantiate it in different places and bind different text property values. That is what we call programmatically altering of text values.
The next point is how we could assign values in QML? As we know QML is a declarative language and it has no explicit operation assignment you may know from other procedural (imperative) languages. In QML we could bind a value in property definition. We may think about this as initializing of the property - the initial value could be changed later. This is similar as well for pre-defined properties as for own defined ones.
Another option is to construct a script block where assignment operation is allowed. There a few cases where we could define a script block. For example the value of an attached property of a signal could be a script block and what we will apply in the following examples.
Following the above ideas for text property altering we could have several approaches as explained bellow.
h2. Direct Binding of a Value
The name of the main QML file is LargeTexts.qml.
LargeTexts.qml
//Main file<br />…<br />//*'''''' Scenario #1 ''''''<br />//We may bind a text when we instantiate the component TextTemplate<br /> TextTemplate {<br /> label: "Another sample text - Hello World&quot;<br /> }<br />// End of Scenario #1<br />…<br />// End of main file<br />
h2. Use of Properties Defined at Top Level
//Main file<br />…<br />//Section of definition of top level entities<br /> property string topproperty:"Locate text block at the beginning of the file&quot;<br />…<br />//*'''''' Scenario #2 ''''''<br />//We want to encapsulate the text block at the beginning of the file<br /> TextTemplate {<br /> label: topproperty
<br /> }<br />// End of Scenario #2<br />…<br />// End of main file<br />
h2. Bind a Value Using QML Binding Element
//Main file<br />…<br />//Section of definition of top level entities<br /> property string newProperty:"Note that value of 'property' item in 'Binding'"''<br />"element is a string - double quotes."<br />…<br />//*'''''' Scenario #3 ''''''<br />//The same as Scenario #2, but using element Binding<br /> Binding {target:bind; property:"label&quot;; value:newProperty}<br /> TextTemplate {id:bind}
// End of Scenario #3<br />…<br />// End of main file<br />
Use onCompleted Attached Property
//Main file<br />…<br />//*'''* The following definitions are used by Scenario #4'''<br /> property string signalText<br /> property string arrayText<br /> Rectangle {<br /> id:startup<br /> Component.onCompleted: {<br /> var complete = "We are using onCompleted property&quot;;<br /> signalText=complete;<br /> var elements= ["text1&quot;,"text2&quot;, "text3&quot;];<br /> arrayText=elements[0];<br /> }<br /> }<br />//*''''''* End of definitions ''''''<br />…<br />//*'''''' Scenario #4 ''''''<br />//We use 'onCompleted' attached property to have a script element and<br />//assign some values
TextTemplate {id:top1<br /> label: signalText<br /> }<br /> TextTemplate {<br /> y:50<br /> paint:"red&quot;<br /> label: arrayText<br /> }
// End of Scenario #4<br />…<br />// End of main file<br />
Apply a JavaScript Inline Function
//Main file<br />…<br />//*'''* The following definitions are used by Scenario #5'''<br /> property string functAssignment:assign(2)<br /> function assign(i) {<br /> var list = ["textFragment1&quot;, "textFragment2&quot;, "textFragment3&quot;];<br /> return list[i];<br /> }<br />//*''''''* End of definitions ''''''<br />…<br />//*'''''' Scenario #5 ''''''<br />//An inline JavaScript function - assign() - is used to assign a value
TextTemplate {<br /> label: functAssignment<br /> }
// End of Scenario #5<br />…<br />// End of main file<br />
The third approach uses JavaScript constructs to define text blocks in a separate .js file. We recall that text property accepts as values anything that result in to a string. For example text property value could be an expression evaluated to a string. Particularly this value could be a string element of a JavaScript array. The scheme is as follows:
//Main file<br />import QtQuick 1.0<br />import "arrayExt.js&quot; as FileExt //This file is used by Scenario #6<br />…<br />//*'''''' Scenario #6 ''''''<br />//An external file - arrayExt.js - contains text blocks
TextTemplate {<br /> label: FileExt.externalArray[2]<br /> }
// End of Scenario #6<br />…<br />// End of main file
//External javaScript file - arrayExt.js<br />/* This external JavaScript file contains the text blocks */<br /> var externalArray = ["textblock1&quot;,"textblock2&quot;,"textblock3 - use backslash to continue&quot;];<br />
Do you really need an array? If you prefer you may have a variable for each text block:
var text1 = "textblock1&quot;;<br />var text2 = "textblock2&quot;;<br />…<br />
How to Format a Multi-line Text
As you know QML supports plain text as well as rich one. There is an essential difference here. QML Text element has built-in properties for text formatting like font.bold, font.pointSize, etc. When we use them they apply to the whole string being value of the text property. If you want to format a text fragment in your text block or even a separate word (symbol) you should use QML rich text mode. This of course supposes you have a background in HTML. Be aware that QML supports a sub-set of HTML/CSS - "consult":http://http://doc.qt.nokia.com/4.7/richtext-html-subset.html for supported HTML/CSS constructs.
The QML runtime includes a JavaScript engine and supports JavaScript, HTML and CSS. For instance, if you create a HTML file with your favorite WYSIWYG HTML editor (without deep HTML coding understanding) it is most probably that QML will accept this file when you define it as a text block. For example this HTML file from my HTML editor works with QML:
<br /><!DOCTYPE html PUBLIC "<s>//W3C//DTD XHTML 1.0 Transitional//EN&quot;
<br />"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;><br />&lt;html &gt;
<br />&lt;head&amp;gt;<br />&lt;meta content="text/html; charset=utf-8&quot; http-equiv="Content-Type&quot; /&amp;gt;<br />&lt;title&amp;gt;Untitled 1&amp;lt;/title&amp;gt;<br />&lt;style type="text/css&quot;&gt;<br /> .auto-style2 {<br /> font-family: "Times New Roman&quot;, Times, serif;<br /> font-size: small;<br /> }<br /> .auto-style3 {<br /> background-color: #FFFF00;<br /> }<br />&lt;/style&amp;gt;<br />&lt;/head&amp;gt;
<br />&lt;body&amp;gt;<br /> <p&gt;<b&gt;Header text&lt;/b&gt;<br/&gt;</p&gt;<br /> <span class="auto-style3&quot;>This is paragraph text&lt;/span&gt; <br /&gt;<br /> <hr /&gt;<br />&lt;/body&amp;gt;
<br />&lt;/html&amp;gt;<br />
Now return to the case of plain text. Suppose we have a text header and a paragraph and want to format them differently for example the header to be bold and colored. The simplest solution is to have two separate Text elements - one for the header and one for the paragraph. The better solution is to
encapsulate somehow the both constructs. To do this we may nest Text elements like this:
<br />import QtQuick 1.0
Rectangle {<br /> width: 360<br /> height: 360<br /> Text {id:top<br /> width:parent.width<br /> color:"lightblue&quot;<br /> font.bold:true<br /> text: "Header Level&quot;<br /> Text {id:nested<br /> anchors.top:parent.bottom<br /> anchors.topMargin:20<br /> width:parent.width<br /> text:"Paragraph Level&quot;<br /> }<br /> }<br /> }<br />
When we are dealing with a multi-line text in QML an important issue is how text is wrapped. Use QML Text element property wrapMode. It takes several "enumerated values":http://doc.qt.nokia.com/4.7/qml-text.html . For example you may use Text.WordWrap as it is done in our text component example. In this mode the text is wrapped on words boundaries. You have to define the Text element width property if want wrapMode to take effect.
You may fix the length of each line in a multi-line text using so called hard breaks. In a plain text use control symbol ' to mark line end. In a rich text we use <br> tag.
<br />Text {id:text4<br /> text:"Plain text - first line\n Plain text - second line\n&quot;<br />}<br />Text {<br /> anchors.top:text4.bottom<br /> text:"<b&gt;Rich text - third line&lt;/b&gt;<br&gt;<i&gt;Rich text - Fourth line&lt;/i&gt;"<br />}<br />
This approach is not recommended especially in cases the text changes often. Instead define the width property of the Text element and apply wrapMode property to have text block adapted to the text frame automatically.
Mixing QML, JavaScript and HTML/CSS constructs it is very easy to run into some syntax issues with some control symbols. The first problem comes from double quotes. They are used in QML as well in HTML/CSS also. The simplest solution seems to be replacing double quotes in text property with single ones or vice-verse. Of course you may use escape sequence ' also like this:
<br />Rectangle {<br /> width: 360<br /> height: 360<br /> Text {id:text1<br /> width:parent.width<br /> text: '<p&gt; <span >Sample text&lt;/span&gt;</p&gt;'<br /> }<br /> Text {id:text2<br /> anchors.top:text1.bottom<br /> text: "<p&gt; <span >Sample text&lt;/span&gt;</p&gt;"<br /> }<br /> Text {id:text3<br /> anchors.top:text2.bottom<br /> text: "<p&gt; <span style=quot;color:blackquot;>Sample text&lt;/span&gt;</p&gt;"<br /> }<br />}<br />
When composing your text block in Qt Quick or other editors you will want to break each line of the text to fit on the screen without any scrolling. If such a block is defined in a script element we have to keep to rules for string splitting in multiple lines. Otherwise you get a message like "Parse error". The proposed solution is: before breaking a text line add a control symbol for string continuation - _. Probably you know it from other programming languages.
<br />Rectangle {<br /> property string new1<br /> property string split<br /> property string how:"String bound to a property<br />is split in two lines&quot;<br /> width: 360<br /> height: 360
Text {id:text0<br /> width:parent.width<br /> text:how<br /> }
Rectangle {<br /> Component.onCompleted: {new1="Not allowed<br />splitting&quot;}<br /> }
Rectangle {<br /> Component.onCompleted: {split="Use backslash to split a string defined in a script element&quot;}<br /> }<br /> Text {id:text00<br /> anchors.top:text0.bottom<br /> text:split<br /> }<br />}<br />
Make Your Text Block Flickable
It is obvious that for bigger text blocks we should make them somehow scrollable. QML offers a very useful construct Flickable for these purposes. Recall the Flickable "construct from":http://doc.qt.nokia.com/4.7/qml-flickable.html. The main question here is what should be the width and height dimensions of the flickable area. You may fix them, but it is not recommendable. The width
property depends on the page design rather. Inherit the width value from Flickable parents. For height property we may use properties binding and calculate Flickable height programmatically. Assume we have three Text elements included in Flickable element that have IDs like this: id:element1,
id:element2 and id:element3. Then Flickable element height property could be calculated as:
<br />Flicable {<br />…<br />height:element1.height+element2.height+element3.height+200<br />…<br />} //end of Flickable<br />
Note: You may get a demo file illustrating the discussed constructs. Download it at "Syncho Server":http://bit.ly/1jNwAAu