Text styles

By default, each of the text controls uses a predefined text style. You can change the appearance of the text by using each control's textStyle property. The textStyle property uses a TextStyleDefinition object, which contains information about a particular text style. You can choose a base style and then customize it by changing visual attributes, such as weight (light, normal, or bold), color, size, and alignment.

It's important to note that a text style is actually represented by a TextStyle object. The TextStyleDefinition is a utility class that lets you produce TextStyle objects and use them as styles in your app. Because using a TextStyleDefinition is a convenient way to create text styles, this is the class that's referred to in this section.

Some properties of TextStyleDefinition accept simple values, and other properties accept enumeration values or constants that are defined in separate classes. For example, you specify a value for the size property by using a float. In contrast, you specify a value for the fontWeight property by using an enumeration value in the  FontWeight class (such as FontWeight::Light or FontWeight::Bold). To determine the values that each property accepts, check the API reference.

Each TextStyleDefinition that you create is an extension of a base style. The base style, which you can specify by using the base property, gives you an initial set of style attributes to work from. You can use the SystemDefaults::TextStyles class to access the default text styles in Cascades. This class contains functions and properties that correspond to styles for large text, small text, title text, and so on.

Screen showing various text styles.

It's a good approach to use one of these default text styles as the base style for your TextStyleDefinition, and then specify values for the properties that you want to change.

Creating a text style in QML

To create a TextStyleDefinition in QML and apply it to a text control, you can define the TextStyleDefinition implicitly in the textStyle property. Or, you can define the TextStyleDefinition explicitly as an attached object and use it in your text control.

Defining a TextStyleDefinition implicitly

You can define a text style directly in a control's textStyle property. You specify values for the different TextStyleDefinition properties (such as basecolor, and so on), and a TextStyleDefinition with these properties is created implicitly and assigned to the control. This can be a good approach if you want the text style to apply to only one control, and you know you won't need to reuse the style for any other controls.

If your app uses many different text styles for different controls, using this approach can consume a lot of memory and adversely affect your app's performance.

Here's how to create two Label controls that each use a different text style. A variety of TextStyleDefinition properties are used to change the appearance of the text.

import bb.cascades 1.0
 
Page {
    content: Container {   
        Label {
            text: "This is a label."
 
            textStyle {
                base: SystemDefaults.TextStyles.BigText
                color: Color.Red
            }
        }
     
        Label {
            text: "This is another label."
         
            textStyle {
                base: SystemDefaults.TextStyles.SmallText
                color: Color.create(0.1, 0.4, 0.8)
                fontStyle: FontStyle.Italic
            }
        }
    } // end of Container
} // end of Page

Defining a TextStyleDefinition explicitly

You can define a text style inside the attachedObjects list of a control, and then use that style in a textStyle property. The process is similar to defining a text style implicitly, but you need to specify an id for the TextStyleDefinition so you can refer to it. After you define the TextStyleDefinition, you can retrieve the style it represents by using the style property. This approach can be ideal when you want to reuse the same style for multiple text controls in your app. You should try to use this approach as often as possible to minimize memory consumption and maximize your app's performance.

Here's how to create a TextStyleDefinition and use it as the base style for a Label.

import bb.cascades 1.0
 
Page {
    content: Container {
        attachedObjects: [
            TextStyleDefinition {
                id: myStyle
                base: SystemDefaults.TextStyles.BodyText
                color: Color.Green
                fontWeight: FontWeight.Bold
            }
        ]
     
        Label {
            text: "A label with some text."
         
            textStyle {
                base: myStyle.style
            }
        }
    } // end of Container
} // end of Page

Creating a text style in C++

You can create a text style in C++ by using the  TextStyle class. You need to retrieve the TextStyleDefinition that applies to a text control by calling AbstractTextControl::textStyle() and then apply your style by calling TextStyleDefinition::setBase().

To minimize memory consumption, you should try to reuse text styles whenever possible. Here's how to create two text styles efficiently and apply them to  Label controls.

// Create the root page and top-level container
Page *root = new Page;
Container *topContainer = new Container;
 
// Create the text styles
TextStyle *blueStyle = new TextStyle(SystemDefaults::TextStyles::smallText());
blueStyle->setColor(Color::Blue);
 
TextStyle *greenStyle = new TextStyle(SystemDefaults::TextStyles::bodyText());
greenStyle->setColor(Color::Green);
 
// Create the labels and set the text style for each one. Notice that the
// setBase() function accepts a dereferenced pointer to the text style as an
// argument.
Label *blueLabel = Label::create()
                   .text("This is a blue label.");
blueLabel->textStyle()->setBase(*blueStyle);
 
Label *greenLabel = Label::create()
                   .text("This is a green label.");
greenLabel->textStyle()->setBase(*greenStyle);
 
Label *anotherBlueLabel = Label::create()
                   .text("This is another blue label.");
anotherBlueLabel->textStyle()->setBase(*blueStyle);
 
// Add the labels to the top-level container and set the content of the page
topContainer->add(blueLabel);
topContainer->add(greenLabel);
topContainer->add(anotherBlueLabel);
root->setContent(topContainer);

Supporting accessibility settings

When possible, it's important to make your apps accessible to a wide range of users. One way to do this is to use the predefined font sizes that Cascades includes. When you create text styles in your apps, you should use the fontSize property and specify one of the predefined enumeration values in FontSize (such as FontSize.XXLarge). By using this approach, the font sizes will change depending on the global font size that a user selects (by using the Font Size option in the Settings app on the device).

Here's how to create a Label that uses a predefined font size:

Label {
    text: "Label"
    textStyle {
        fontSize: FontSize.XXLarge
    }
}

You should use this approach instead of using the fontSizeValue property and specifying a fixed font size.

Font family support

Cascades supports a range of font families, including:

  • Andale Mono
  • Arial
  • Arial Black
  • Comic Sans MS
  • Courier New
  • DejaVu Sans
  • DejaVu Sans Condensed
  • DejaVu Sans Mono
  • DejaVu Serif
  • DejaVu Serif Condensed
  • Georgia
  • Impact
  • MT Extra
  • Slate Pro
  • Symbol
  • Tahoma
  • Times New Roman
  • Trebuchet MS
  • Verdana
  • Webdings
  • Webdings 2
  • Webdings 3

In addition to the specific fonts listed above, Cascades also supports a number of generic font families. The generic font families include:

  • Sans-Serif
  • Serif
  • Monospace
  • Cursive
  • Fantasy

When you set a generic font family as a fallback, if a character is not found in the specified primary font, Cascades chooses a suitable font from the specified font family. If a generic font family is not specified and a character is not found, Cascades uses a Sans-Serif fallback font by default.

Best practices

As a best practice, you should avoid explicitly specifying a font family. Since Cascades chooses a font family based on the current theme and user settings of a device, explicitly specifying a font family can override these settings.

If you choose to specify a primary font family you should always specify a generic font family as a fallback to guard against font replacement.

Specifying a font family in QML

To use one of the supported font families in your app, you specify the font family in the fontFamily attribute. To specify a generic font family as a fallback, you specify the generic font family as the last item in a comma-seperated list.

Label {
    id: label
    text: inputtext.text
    textStyle {
        base: SystemDefaults.TextStyles.NormalText
        color: Color.Gray
        fontFamily: 'Verdana, Sans-Serif'
    }
}

You can also use HTML markup to specify a font family:

Label{
    id: label
    text: “<html><span style="font-family:Helvetica,Arial,Sans-Serif;">This text will render in Arial on BB10</span></html>”
}

HTML text styling

Using a TextStyleDefinition to apply text styles to your UI controls, as described in the previous section, can be a good way to reuse a specific text style throughout your app. This approach can help you create a consistent visual appearance, as well as save memory and processing time.

However, you might want to apply a style to individual text elements, such as a single word or paragraph. When you use a TextStyleDefinition, you can apply only a single, uniform style to the entire text of a control. If you want to apply a style to specific parts of the text, you can use inline HTML to apply the styles that you want.

Cascades supports a subset of the XHTML specification. You can use certain HTML elements to apply styles to the text in your controls. For example, you can use the <b> tag (and its associated end tag, </b>) to apply a bold style to text, and you can use the <i> and </i> tags to apply an italic style. You can also use more complex HTML elements, such as <span> and <div>, to apply basic CSS style properties to your text. By using a combination of HTML elements and CSS properties, you have access to more text formatting options than those provided by TextStyleDefinition.

Here's a list of the HTML elements that Cascades supports:

<a>

This element represents a hyperlink. You can include the href and style attributes in this element.

<b>

This element renders text using a bold style.

<br/>

This element represents a line break. Using this element inserts a forced line break character into the text. It's important to note that only the closed-tag notation (<br/>) is supported, not the opening tag by itself (<br>).

This element has no effect if you use it inside a control that has a predefined height (such as a TextField).

<i>

This element renders text using an italic style.

<span>

This element provides a generic way to add structure or formatting to text. You can include the style attribute in this element, which is used to apply CSS styles to the text.

<p>

This element represents a paragraph. Paragraph spacing is added before and after this element. You can include the style attribute in this element, which is used to apply CSS styles to the text.

<div>

This element represents a section. Paragraph spacing is added before and after this element. You can include the style attribute in this element, which is used to apply CSS styles to the text.

<em>

This element represents emphasized text. This type of text is implemented using an italic style.

<strong>

This element represents strong text. This type of text is implemented using a bold style.

To apply a text style using inline HTML, you can add the appropriate HTML elements inside the text property of the control. All of the HTML elements that you use must be placed between <html> and </html> tags. Here's how to apply two text styles, bold and italic, to different words in a TextArea using QML.

Screen showing inline HTML styling.
import bb.cascades 1.0

Page {
    TextArea {
        preferredWidth: 255
        text: "<html><b>Cascades</b> is <i>awesome!</i></html>"
    }
}

Here's how to do the same thing in C++.

// Create the root page and text area
Page *root = new Page;
TextArea *textArea = new TextArea;

// Set the preferred width and text
textArea->setPreferredWidth(255);
textArea->setText("<html><b>Cascades</b> is <i>awesome!</i></html>");

// Set the content of the page
root->setContent(textArea);

You should make sure that the HTML markup that you use is well-formed and doesn't contain any errors. If there are any errors in the markup (for example, typographic errors, syntax errors, unclosed HTML elements, and so on), the text is treated as raw, unformatted text.

You can use inline HTML to apply styles to the text of any UI control in Cascades. If you use inline HTML in a TextField or TextArea, any text that a user types in these controls is interpreted as plain text. In other words, a user can't type additional HTML tags inside these controls and apply new styles to the text as the app is running. However, the text that the user types inherits the style that's already applied at the current cursor position inside the control. For example, if you use the <i> element to apply an italic style to text in a TextField, when a user types inside the TextField, the typed text is also in italic style.

Cascades also supports a set of XHTML character entities. These character entities let you insert less common characters in your text. For example, the character entity &amp; represents the ampersand (&) character. You can also use character entities to insert characters that would otherwise interfere with the XHTML syntax, such as the less than sign (<) and greater than sign (>). Here's a list of the character entities that Cascades supports:

&lt;
Represents a less than sign (<)
&gt;
Represents a greater than sign (>)
&amp;
Represents an ampersand (&)
&quot;
Represents a neutral double quotation mark (")
&apos;
Represents a neutral single quotation mark or apostrophe (')
&#number
Allows you to specify a character using its Unicode code point (in decimal form)
&#xNumber
Allows you to specify a character using its Unicode code point (in hexadecimal form)

Using CSS to apply text styles

In addition to the HTML styling elements that are described above, you can also use basic CSS to apply styles to text. You can use CSS to change text properties such as background color, direction, font size, alignment, and so on. This approach is available when you use HTML elements that support the style attribute (for example, <span> and <div>), and you must specify the CSS style properties inline by using this attribute.

Here's a list of the CSS properties that Cascades supports:

Property Description Possible values
background-color Sets the background color <color> (Supports 147 standard color names, such as "blue" and "green", as well as rgb(n,n,n), rgba(n,n,n,n), hsl(n,n,n), hsla(n,n,n,n) and #NNNNNN)
color Sets the text color <color> (Supports 147 standard color names, such as "blue" and "green", as well as rgb(n,n,n), rgba(n,n,n,n), hsl(n,n,n), hsla(n,n,n,n) and #NNNNNN)
direction Specifies the direction of the text (left-to-right or right-to-left) [ ltr | rtl ]
font-family Specifies the font family

<family-name> (Supports font family names such as "Arial" and "Verdana")

<generic-family> (Supports generic font family names such as "Sans-Serif" and "Monospace")

Multiple values can be used together in a comma-seperated list to provide a fallback font in the event that a primary font is not present on the platform or a character from the specified primary font can't be found

font-size Specifies the font size [ xx-small | x-small | small | medium | large | x-large | xx-large | smaller | larger | <dimension> ]
font-style Specifies the font style [ normal | italic | oblique ]
font-weight Specifies the font weight [ normal | bold | lighter | bolder | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 ]
line-height Specifies the height of a line of text [ normal | <multiplier> | <dimension> ]
text-align Specifies the horizontal alignment [ left | right | center | justify ]
text-decoration Turns on or turns off underlining or line-through (strike-through) [underline | line-through | none ]
letter-spacing Adjusts the space between letters in the text <dimension>

In the table above, <dimension> is a number followed by a unit:

  • % (percentage of the parent element's value)
  • pt (printer's point)
  • pc (printer's pica)
  • in (inch)
  • cm (centimeter)
  • mm (millimeter)
  • em (printer's em, which is equal to the current font size)
  • ex (printer's ex height, which is equal to 0.5em when the ex height is not known)

Here's how to create a TextArea with various CSS properties, in QML. This code sample uses properties such as text-decoration, font-size, and font-style to add styles to different parts of the TextArea.

Screen showing CSS properties applied to a Label control.
import bb.cascades 1.0

Page {
    TextArea {
        preferredWidth: 325
        text: "<html><span style='text-decoration:underline'>Cascades</span>
               is <span style='font-size:xx-large;font-style:italic;color:green'>
               awesome!</span></html>"
    }
}

Here's how to do the same thing in C++.

// Create the root page and text area
Page *root = new Page;
TextArea *textArea = new TextArea;

// Set the preferred width and text
textArea->setPreferredWidth(325);
textArea->setText("<html><span style='text-decoration:underline'>Cascades</span>
                          is <span style='font-size:xx-large;font-style:italic;
                          color:green'>awesome!</span></html>");

// Set the content of the page
root->setContent(textArea);

Internal CSS definitions

As described in the previous section, you can use inline HTML to apply styles to the text in your app. This approach can work well if you have only a few styles that you want to use, or if each style is slightly different and you want to have precise control over how the text in your app looks. You can even use a variety of CSS properties to customize your styles.

There might be cases where you want to use the power of CSS but need to be able to reuse your styles in different areas of your text controls. Or, you might want to read a set of CSS properties from a file on the device's file system and apply those properties to your text.

Fortunately, Cascades supports the use of internal CSS definitions, which let you define a full set of CSS styles directly in your text controls. By using internal CSS definitions, you can use CSS properties to apply a consistent style to each element that you use. For example, you can specify that each <p> element should use a bold font and be blue, or you can specify that each <h1> element should use an italic font and be green.

There are a few conditions that need to be met in order to use an internal CSS definition in a text control:

  • The text in the control must be contained entirely in an <html> element (that is, between <html> and </html> tags).
  • The first element inside <html> must be a <head> element.
  • The first <head> element inside <html> must contain at least one <style> element.
  • The text of each <style> element must contain valid, complete CSS syntax (that is, the <style> element must contain whole rules or other CSS elements).

Similar to applying inline HTML styles to text controls, you specify your CSS in the text property of a text control. The code sample below shows you how to create an internal CSS definition for a TextArea in QML. This definition applies an italic style to text in <p> elements, and it also applies a custom style (bold and colored red) to hyperlinks of the form <a href='...'>.

It's important to note that when you specify a style for hyperlinks using :link, this style applies to all links that are automatically detected in your text controls. This approach is the only way to apply a style to auto-detected links (also known as active text) in Cascades.

import bb.cascades 1.0

Page {
    TextArea {
        text: "<html><head><style>
                   p {font-style:italic;}
                   a:link {font-weight:bold;color:red}
               </style></head>
               <p>This text uses an italic style.</p>
               <p><a href='http://developer.blackberry.com'>This is a hyperlink.
                  </a></p>
               </html>"
    }
}

To make it easier to see the structure of the CSS definition, the example above includes indentation and additional whitespace in the value of the text property. To prevent line breaks or other formatting issues in your text, when you use internal CSS definitions in your own app, you should keep the property value on one line.

To specify which elements you want to style, you can use CSS selectors. Cascades supports several types of selectors, which are outlined in the table below. The table provides the general syntax of the selector, a brief description, and an example of how you might use the selector in a <style> element in your own text controls.

Selector syntax Description Example
* Matches any element * {background-color:#e0ffff;}
E Matches any element called E h1 {font-size:40px;}
E:link Matches a hyperlink that's defined using <a href='...'> and also matches the attribute _activeLink a:link {font-size:21px;color:#BBBBBB;}
E[attr] Matches the element E that includes the attr attribute p[title] {color:blue;}
E[attr='val'] Matches the element E that includes the attr attribute with the value val a[href='http://www.rim.com/'] {color:green;}
E[attr~='val'] Matches the element E that includes the attr attribute with the value val as part of a space-separated list

a[title~='warning'] {color:red;}

a[title~='info'] {color:green;}

...

<a title='Important warning' href='http://warninglink.com'>Warning </a>

<a title='Vital info' href='http://infolink.com'>Info</a>

E[lang|=en] Matches the element E with a language of en or en-X , where X is any value

[lang|=en] {color:blue;}

...

<p lang='en'>Hello!</p>

<p lang='en-us'>Hi!</p>

.myclass Matches any element where class='myclass'

.centered {text-align:center;color:red;}

...

<h1 class='centered'>Center-aligned red heading</h1>

E#myID Matches any element where id='myID'

p#firstparagraph{color:red;}

...

<p id='firstparagraph'>Hello World!</p>

To learn more about the syntax of any of these selectors, see Selectors on the W3C website.

Emoji

Emoji are a special type of emoticon that originated in Japanese electronic messages and webpages and are now used in many apps all over the world.

Emoji have Unicode numbers assigned to them and provide a wider range of icons than standard emoticons. For example, there are emoji that depict weather conditions (sun, clouds, thunderstorms), astrological signs (Pisces, Capricorn, Taurus), vehicles (cars, buses, aircraft), and so on.

Screen showing examples of emoji.

Cascades supports the use of emoji in text controls in your apps. Emoji support is always enabled for all Cascades text controls, such as Label, TextArea, and TextField controls. One way to specify an emoji is to use its Unicode value and place the value inside an <html> element in your text control. For example, the Unicode value for the cloud emoji is 0x2601. To include the cloud emoji in a text control, you can specify <html>&#x2601;</html> in the text property of the control.

Cascades supports two mappings for emoji:

  • Standard Unicode mapping: This mapping contains values for emoji that are included in the Unicode standard. These values typically begin at U+2600 and are sequential. For a full list of Unicode values, visit The Unicode Consortium website. Note that Cascades doesn't support the full range of Unicode values, but support for additional values will be added in the future.
  • Private-range DoCoMo mapping: This mapping contains private-range values that are used by DoCoMo. These values typically use a range of E63E to E757 in the Unicode character space.

When you add emoji to text controls in your app and you preview your app using the QML preview in the Momentics IDE, you might not see the emoji in the preview. You might see only a placeholder image for each emoji. To see the emoji, you should run your app on a BlackBerry 10 device or simulator.

Here's how to create several Label controls that contain emoji in QML. This code sample uses private-range DoCoMo values to specify the emoji to use. You can use the same approach to add emoji to other text controls, such as TextArea and TextField controls.

import bb.cascades 1.0

Page {
    Container {
        layout: StackLayout {}

        Label {
            text: "<html>&#xE63E;  Sunny: Get your vitamin D</html>"
        }
        
        Label {
            text: "<html>&#xE63F;  Partly cloudy: Might need a coat</html>"
        }
        
        Label {
            text: "<html>&#xE640;  Rain: Bring your umbrella</html>"
        }
        
        Label {
            text: "<html>&#xE641;  Snow: Don't forget the carrot nose</html>"
        }
        
        Label {
            text: "<html>&#xE642;  Thunderstorm: No metal!</html>"
        }
    }
}

In C++, there are a couple of approaches that you can use to add emoji. You can use HTML directly (similar to the approach that's used in QML) or you can use the Unicode converter function, QString::fromUtf8(), that's provided by the Qt framework. Here's how to use both approaches:

// Create a label and set its text using HTML
Label *sunnyLabel = new Label();
sunnyLabel->setText("<html>&#xE63E;</html>");

// Create a label and set its text using the Unicode converter
// function
Label *cloudyLabel = new Label();
cloudyLabel->setText(QString::fromUtf8("\uE63F"));

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus