QT QString very full use (turn)

Source: Internet
Author: User
Tags pear

QString, Qbytearray, and qvariant these three classes and containers have many similarities, and in some cases can be treated as special containers. Similarly, like containers, these classes use implicit sharing to optimize memory and speed.

We'll start with the qstring. Strings are used by each GUI program, not only the user interface but also the data structure. C + + native provides two types of strings: the traditional C-style array of characters ending with ' std::string ' and the class. Unlike these, qstring uses 16-bit Unicode values. Unicode contains the subset of ASCII and Latin-1 and their normal values. And Qstring is 16-bit, so it can represent the characters of most languages in the world. For more information on Unicode, see Chapter 17.

When using qstring, we don't have to worry about such secret details as allocating enough memory or ending with the data as '/'. In general, qstring can be thought of as a qchar vector. A qstring can embed the ' \ S ' character. The length () function returns the entire string size, including the embedded ' + '.

The qstring provides a $ two + operator to concatenate two strings and A + = operator to append a string to a string. Because qstring automatically pre-allocates memory at the end of the string, it is very fast to add a string by appending the characters repeatedly. This is an example of a + and + = combination:

QString str = "User:"; str + = UserName + "\ n";

There is also a qstring::append () function that has the same function as the + = operator:

str = "User:"; Str.append (UserName); Str.append ("\ n");

A completely different way to combine strings is to use the qstring sprintf () function:

str.sprintf ("%s%.1f%%", "perfect competition", 100.0);

Supports the same format specifier as the sprintf () function of the C + + library. In the example above, STR is assigned the value "perfect competition 100%".

Another way to build a string from another string or number is to use ARG ():

str = QString ("%1%2 (%3s-%4s)"). Arg ("permissive"). Arg ("society"). Arg (1950). Arg (1970);

In this example, "%1" is replaced by "permissive", "%2 is replaced by" society ","%3 "is replaced by" 1950 ", and"%4 "is replaced by" 1970 ". The result is "permissive society (1950s-1970s)". The ARG () overload supports a wide variety of data types. Some overloads have additional parameters to control the field width, number cardinality, or floating point precision. Normally, Arg () is a better solution than sprintf () because it is type-safe (type-safe), fully Unicode-enabled, and allows translators to reorder the "%n" parameters.

Qstring can convert a number to a string by using the static function Qstring::number ():

str = Qstring::number (59.6);

or use the Setnum () function:

Str.setnum (59.6);

The inverse transformation is to convert a string into a number, using ToInt (), Tolonglong (), ToDouble (), and so on. For example:

BOOL OK; Double d = str.todouble (&ok);

These functions accept a pointer of an optional BOOL type and set the bool variable to TRUE or false, depending on whether the conversion succeeds or not. If the conversion fails, these functions return 0.

Once we have a string, we often want to extract some parts of it. The mid () function returns a string of the given starting position (the first argument) and the length (the second argument). For example, the following code prints "pays" on the console: [*]

[*] using the useful qdebug () << arg syntax requires the inclusion of a header file, while the Qdebug ("...", ARG) syntax is available in any file containing at least one QT header file.

QString str = "polluter pays principle"; Qdebug () << Str.mid (9, 4);

If the second argument is omitted, mid () returns a substring from the specified starting position to the end of the string. For example, the following code prints "pays principle" on the console:

QString str = "polluter pays principle"; Qdebug () << Str.mid (9);

There is also the left () and right () functions, which also perform similar work. They both accept a number that represents the number of characters, N, and return and return the first or last n characters. For example, the following code prints "polluter principle" on the console:

QString str = "polluter pays principle"; Qdebug () << str.left (8) << "<< str.right (9);

If we want to find out whether a string contains a character, string, or regular expression, we can use one of the qstring's indexof () functions:

QString str = "the middle bit"; int i = Str.indexof ("Middle");

I will be placed at 4. The IndexOf () function returns 1 on failure and accepts an optional start position and case sensitive flag.

If we want to check whether a string starts or ends with something, we can use the StartsWith () and EndsWith () functions:

if (Url.startswith ("http:") && Url.endswith (". png") ...

This is simpler and faster than the following:

if (Url.left (5) = = "http:" && url.right (4) = = ". png") ...

String comparisons using the = = operator are case-sensitive. If we are comparing user-level (user-visible) strings, Localeawarecompare () is often the right choice, and if we want case insensitivity, we can use ToUpper () or ToLower (). For example:

if (filename.tolower () = = "Readme.txt") ...

If we want to replace a part of another string with one string, replace () can be used:

QString str = "A cloudy Day"; Str.replace (2, 6, "Sunny");

The result is "a sunny day". You can use remove () and insert () instead:

Str.remove (2, 6); Str.insert (2, "Sunny");

First, we delete the 6 characters starting at position 2, produce a string "a day" (with two spaces), and then we insert "Sunny" at position 2.

There are overloaded versions of replace (), which can replace all occurrences of the first parameter with the second parameter. For example, this is how to replace all occurrences of "&" with "&":

Str.replace ("&", "&");

A common requirement is to filter out whitespace characters (such as spaces, tabs, and newline characters) in the string. Qstring has a function to remove whitespace from both ends of a string:

QString str = "BOB \ t \ the \ndog \ n"; Qdebug () << str.trimmed ();

The string str can be described as:

The string returned by trimmed () is:

When working with user input, we often want to replace one or more internal whitespace characters with a single space, and also filter out whitespace on both ends. This is what the simplified () function does:

QString str = "BOB \ t \ the \ndog \ n"; Qdebug () << str.simplified ();

The string returned by simplified () is:

A string can be divided into a qstringlist with a substring, by using qstring::split ():

QString str = "polluter pays principle"; Qstringlist words = Str.split ("");

In the above example, we divide the "polluter pays principle" into three substrings: "Polluter", "pays", and "principle". The split () function has an optional third parameter (the translator note: The Qt4.4 version should be the second parameter) to decide whether to keep (default) or discard empty substrings.

Qstringlist can be composed of a single string, by using join (). The parameters of join () are inserted between each pair of strings that are combined. For example, here's how to create a single string that consists of strings in qstringlist, sorted alphabetically between strings and separated by newline characters:

Words.sort (); str = words.join ("\ n");

When working with strings, we often need to determine if a string is empty. The purpose can be achieved by calling IsEmpty () or checking if length () is 0.

In most cases, the conversion from the const char * string to the qstring is automatic, for example:

str + = "(1870)";

Here we add a const char * to a qstring, without any constraints. To convert a const char * display to a qstring, simply use a qstring cast, or call Fromascii () or fromLatin1 (). (See Chapter of a explanation of handling literal strings in other encodings.)

To convert a qstring to a const char *, use TOASCII () or toLatin1 (). These functions return a qbytearray, which can be converted to a const char *, by using Qbytearray::d ata () or Qbytearray::constdata (). For example:

printf ("User:%s\n", Str.toascii (). data ());

For convenience, QT provides qprintable () macros, which perform the same operations as TOASCII (). Constdata ().

printf ("User:%s\n", qprintable (str));

When we raise the data () or Constdata () in a Qbytearray, the returned string belongs to the Qbytearray object. This means we don't have to worry about memory leaks; Qt will reclaim memory for us. On the other hand, we are careful not to use this pointer for too long. If Qbytearray is not stored in a variable, it will be automatically deleted at the end of the statement.

Qbytearray has an API similar to qstring. Like left (), right (), Mid (), ToLower (), ToUpper (), trimmed (), and simplified () have the same semantics for the corresponding functions in Qbytearray and qstring. Qbytearray is useful for storing pure binary data (raw binary) and 8-bit encoded text strings. In general, we recommend using qstring to store text instead of Qbytearray, because Qstring supports Unicode.

For convenience, Qbytearray automatically ensures that the "one past the last" byte is always ' on ', making it easy to pass a qbytearray to a function with a const char * type parameter. Qbytearray also supports the inline ' \ s ' character, which allows us to store any binary data (arbitrary binary).

In some cases, we need to store different types of data with a single variable. One process is to encode data into a qbytearray or a qstring. For example, a string can hold a literal value or a numeric value in string form. These processes are flexible, but they erase the benefits of C + +, especially type safety and efficiency. QT provides a cleaner way to handle variables that support different types. Qvariant.

The Qvariant class supports many QT-type values, including Qbrush, Qcolor, Qcursor, Qdatetime, Qfont, Qkeysequence, Qpalette, Qpen,qpixmap, Qpoint, QRect, QR Egion, Qsize, and qstring, and basic C + + numeric types, like double and int. The Qvariant class also supports containers: Qmap<qstring,qvariant>, Qstringlist, and Qlist.

The mutable type (variants) is widely used by the bar visual class (Item view classes), database module, and Qsettings, which allows us to read and write entry data, database data, and user parameters of any type compatible with Qvariant. We have seen this example in Chapter three, we pass a qrect, a qstringlist, and a pair of bool as mutable types to Qsettings::setvalue () and dereference them as mutable types.

It is possible to create arbitrary complex data structures by using Qvariant to apply the container's value type:

Qmap<qstring, qvariant= "" > Pearmap; pearmap["standard"] = 1.95; pearmap["Organic"] = 2.25; Qmap<qstring, qvariant= "" > Fruitmap; fruitmap["Orange"] = 2.10; fruitmap["Pineapple"] = 3.85; fruitmap["Pear"] = Pearmap;

We have created a map whose key is a string (product name) whose value is floating point (price) or maps. The top-level map consists of three keys: "Orange", "Pear", and "Pineapple". The value associated with the "Pear" key is a map that contains two keys ("Standard" and "Organic"). When iterating over a container that holds a mutable type value, we need to use type () to examine the types held by the mutable type so that we can respond appropriately.

Creating data structures like this is fascinating because we can organize data in the way we like. However, the convenience of qvariant leads to the loss of performance and readability. In general, whenever possible, it is worthwhile to use it to define an appropriate C + + class to store our data.

Qvariant is used by the QT meta-object system and is therefore part of the Qtcore module. However, when we connect the Qtgui module, qvariant can store gui-related types such as Qcolor, Qfont, Qicon, Qimage, and Qpixmap:

Qicon icon ("Open.png"); Qvariant variant = icon;

In order to dereference the gui-related type value from Qvariant, we can use the Qvariant::value () template function as follows:

Qicon icon = Variant.value ();

Value () is also used to convert between the Non-gui data type and qvariant, but in practice we generally use the to for the Non-gui type ... () conversion function (for example, toString ()).

Qvariant can also be used to save custom data types if they provide a default constructor and a copy constructor. For this to work, we must first use the Q_declare_metatype () macro registration type, placed below the class definition in the header file:

Q_declare_metatype (Businesscard)

This allows us to write code like this:

Businesscard Businesscard; Qvariant variant = Qvariant::fromvalue (Businesscard); ... if (Variant.canconvert ()) {Businesscard card = Variant.value (); ...}

Because of compiler limitations, these template functions are not available in Msvc 6. If you need to use this compiler, use the global function Qvariantfromvalue (), Qvariantvalue (), and Qvariantcanconvert () instead.

If the custom data type has << and >> operators in order to read a qdatastream, we can register them with qregistermetatypestreamoperators (). In addition, this makes it possible to store parameters for custom data types through qsettings. For example:

Qregistermetatypestreamoperators ("Businesscard");

This chapter focuses on QT containers, as well as qstring, Qbytearray, and Qvariant. In addition to these classes, QT also provides some other containers. One is qpair<t1, t2= "", it simply stores two values, similar to std::p air<t1, t2= "" >. The other is Qbitarray, which we will use in the first section of chapter 19th. Finally, a lower-level alternative to qvarlengtharray<t,prealloc>,qvector (low-level alternative). Because it pre-allocates memory on the stack and is not implicitly shared, it is less expensive than qvector, making it suitable for efficient loops (tight loops).

QT algorithms, including some not mentioned here like Qcopybackward () and qequal (), are described in the QT documentation http://doc.trolltech.com/4.1/algorithms.html. For more information on QT containers, including their time complexity and growth strategy, see http://doc.trolltech.com/4.1/containers.html.

QT QString very full use (turn)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.