Qt5 как поместить qstring в структуру
Перейти к содержимому

Qt5 как поместить qstring в структуру

  • автор:

Qt, передающий QString в конструктор структуры, не работает

Я не кодировал C ++ уже несколько лет, но мне кажется, что я неправильно передаю строку, и мне нужно иметь некоторое кунг-фу, связанное с передачей по ссылке, указателями и копированием и записью.

Теория есть, но мои практические навыки меня сегодня ужасно подводят. Кто-нибудь может помочь?

задан 07 мая ’13, 14:05

Как проверить, что он не работает? — Joseph Mansfield

Я проверяю, устанавливая точки останова в коде и проверяя переменные при отладке. — josef.van.niekerk

Хорошо, проблема не в строке hidData->append. — josef.van.niekerk

Не имеет отношения к этой конкретной проблеме, но вы можете исправить эту утечку памяти; вы без необходимости создаете объект с new , копируя его, а затем отбрасывая указатель. Пытаться hidData->append(HidItem(«USAGE_PAGE, 1)) вместо. — Mike Seymour

@josef.van.niekerk: Кроме того, hidData вероятно должен быть QVector объект, а не указатель. Лучше избегать new если вам это действительно не нужно. — Mike Seymour

1 ответы

Работает для меня:

Одна вещь, которую вы должны изменить, это подпись HidItem конструктор, так что он ожидает константную ссылку вместо объекта:

Это позволяет избежать ненужного создания временных объектов. Но тем не менее, ваш подход также работает хорошо.

Настоящая проблема заключается в неправильном использовании конструктора QVector:

добавляет hidItem как элемент #11, так как QVector уже содержит 10 элементов после создания.

(и рассмотреть замечания относительно new @Майк Сеймур).

ответ дан 07 мая ’13, 14:05

Спасибо, Андреас, я только что понял, что моя проблема связана с hidData->append(*(hidItem)); линия. Когда я пытаюсь получить данные, используя, например, hidData->at(0).name, я ничего не получаю. — Йозеф Ван Никерк

Спасибо за совет qDebug(), не знал, что вы можете это сделать. 😉 — Йозеф Ван Никерк

Вау, спасибо! Мой C++ не только заржавел за эти годы, я думаю, что на нем росла плесень. D — Йозеф Ван Никерк

@josef.van.niekerk Нет проблем — вы недавно программировали на Java? java.util.Vector API ведет себя так, как вы ожидали в своем коде 😉 — Андреас Фестер

Я занимался Java несколько месяцев назад над проектом, над которым работал, да, но точно не помню, чтобы использовал Vector. Я помню, как использовал другие классы коллекций. — Йозеф Ван Никерк

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c++ qt or задайте свой вопрос.

Qt5 как поместить qstring в структуру

Note: All functions in this class are reentrant.

Public Types

ConstIterator
Iterator
enum NormalizationForm
enum SectionFlag
flags SectionFlags
const_iterator
const_pointer
const_reference
const_reverse_iterator
difference_type
iterator
pointer
reference
reverse_iterator
size_type
value_type

Public Functions

Static Public Members

QString asprintf(const char *cformat, . )
int compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, QLatin1String s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(QLatin1String s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, QStringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(QStringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString fromCFString(CFStringRef string)
QString fromLatin1(const char *str, qsizetype size)
QString fromLatin1(QByteArrayView str)
QString fromLatin1(const QByteArray &str)
QString fromLocal8Bit(const char *str, qsizetype size)
QString fromLocal8Bit(QByteArrayView str)
QString fromLocal8Bit(const QByteArray &str)
QString fromNSString(const NSString *string)
QString fromRawData(const QChar *unicode, qsizetype size)
QString fromStdString(const std::string &str)
QString fromStdU16String(const std::u16string &str)
QString fromStdU32String(const std::u32string &str)
QString fromStdWString(const std::wstring &str)
QString fromUcs4(const char32_t *unicode, qsizetype size = -1)
QString fromUtf8(const char *str, qsizetype size)
QString fromUtf8(QByteArrayView str)
QString fromUtf8(const QByteArray &str)
QString fromUtf8(const char8_t *str)
QString fromUtf8(const char8_t *str, qsizetype size)
QString fromUtf16(const char16_t *unicode, qsizetype size = -1)
QString fromWCharArray(const wchar_t *string, qsizetype size = -1)
int localeAwareCompare(const QString &s1, const QString &s2)
int localeAwareCompare(QStringView s1, QStringView s2)
QString number(long n, int base = 10)
QString number(int n, int base = 10)
QString number(uint n, int base = 10)
QString number(ulong n, int base = 10)
QString number(qlonglong n, int base = 10)
QString number(qulonglong n, int base = 10)
QString number(double n, char format = ‘g’, int precision = 6)
QString vasprintf(const char *cformat, va_list ap)

Related Non-Members

qsizetype erase(QString &s, const T &t)
qsizetype erase_if(QString &s, Predicate pred)
bool operator!=(const QString &s1, const QString &s2)
bool operator!=(const QString &s1, QLatin1String s2)
bool operator!=(const char *s1, const QString &s2)
QString operator»»_qs(const char16_t *str, size_t size)
const QString operator+(const QString &s1, const QString &s2)
const QString operator+(const QString &s1, const char *s2)
const QString operator+(const char *s1, const QString &s2)
bool operator<(const QString &s1, const QString &s2)
bool operator<(const QString &s1, QLatin1String s2)
bool operator<(QLatin1String s1, const QString &s2)
bool operator<(const char *s1, const QString &s2)
QDataStream & operator<<(QDataStream &stream, const QString &string)
bool operator<=(const QString &s1, const QString &s2)
bool operator<=(const QString &s1, QLatin1String s2)
bool operator<=(QLatin1String s1, const QString &s2)
bool operator<=(const char *s1, const QString &s2)
bool operator==(const QString &s1, const QString &s2)
bool operator==(const QString &s1, QLatin1String s2)
bool operator==(QLatin1String s1, const QString &s2)
bool operator==(const char *s1, const QString &s2)
bool operator>(const QString &s1, const QString &s2)
bool operator>(const QString &s1, QLatin1String s2)
bool operator>(QLatin1String s1, const QString &s2)
bool operator>(const char *s1, const QString &s2)
bool operator>=(const QString &s1, const QString &s2)
bool operator>=(const QString &s1, QLatin1String s2)
bool operator>=(QLatin1String s1, const QString &s2)
bool operator>=(const char *s1, const QString &s2)
QDataStream & operator>>(QDataStream &stream, QString &string)

Macros

QStringLiteral(str)
QT_NO_CAST_FROM_ASCII
QT_NO_CAST_TO_ASCII
QT_RESTRICTED_CAST_FROM_ASCII

Detailed Description

QString stores a string of 16-bit QChars, where each QChar corresponds to one UTF-16 code unit. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)

Unicode is an international standard that supports most of the writing systems in use today. It is a superset of US-ASCII (ANSI X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1 characters are available at the same code positions.

Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.

In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit ‘\0’-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application’s market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (like in embedded systems).

Initializing a String

One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data «Hello»:

QString converts the const char * data into Unicode using the fromUtf8() function.

In all of the QString functions that take const char * parameters, the const char * is interpreted as a classic C-style ‘\0’-terminated string encoded in UTF-8. It is legal for the const char * parameter to be nullptr .

You can also provide string data as an array of QChars:

QString makes a deep copy of the QChar data, so you can modify it later without experiencing side effects. (If for performance reasons you don’t want to take a deep copy of the character data, use QString::fromRawData() instead.)

Another approach is to set the size of the string using resize() and to initialize the data character per character. QString uses 0-based indexes, just like C++ arrays. To access the character at a particular index position, you can use operator[](). On non- const strings, operator[]() returns a reference to a character that can be used on the left side of an assignment. For example:

For read-only access, an alternative syntax is to use the at() function:

The at() function can be faster than operator[](), because it never causes a deep copy to occur. Alternatively, use the first(), last(), or sliced() functions to extract several characters at a time.

A QString can embed ‘\0’ characters (QChar::Null). The size() function always returns the size of the whole string, including embedded ‘\0’ characters.

After a call to the resize() function, newly allocated characters have undefined values. To set all the characters in the string to a particular value, use the fill() function.

QString provides dozens of overloads designed to simplify string usage. For example, if you want to compare a QString with a string literal, you can write code like this and it will work as expected:

You can also pass string literals to functions that take QStrings as arguments, invoking the QString(const char *) constructor. Similarly, you can pass a QString to a function that takes a const char * argument using the qPrintable() macro which returns the given QString as a const char * . This is equivalent to calling <QString>.toLocal8Bit().constData().

Manipulating String Data

QString provides the following basic functions for modifying the character data: append(), prepend(), insert(), replace(), and remove(). For example:

In the above example the replace() function’s first two arguments are the position from which to start replacing and the number of characters that should be replaced.

When data-modifying functions increase the size of the string, they may lead to reallocation of memory for the QString object. When this happens, QString expands by more than it immediately needs so as to have space for further expansion without reallocation until the size of the string has greatly increased.

The insert(), remove() and, when replacing a sub-string with one of different size, replace() functions can be slow (linear time) for large strings, because they require moving many characters in the string by at least one position in memory.

If you are building a QString gradually and know in advance approximately how many characters the QString will contain, you can call reserve(), asking QString to preallocate a certain amount of memory. You can also call capacity() to find out how much memory the QString actually has allocated.

QString provides STL-style iterators (QString::const_iterator and QString::iterator). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.

Note: Iterators over a QString, and references to individual characters within one, cannot be relied on to remain valid when any non- const method of the QString is called. Accessing such an iterator or reference after the call to a non- const method leads to undefined behavior. When stability for iterator-like functionality is required, you should use indexes instead of iterators as they are not tied to QString’s internal state and thus do not get invalidated.

Note: Due to implicit sharing, the first non- const operator or function used on a given QString may cause it to, internally, perform a deep copy of its data. This invalidates all iterators over the string and references to individual characters within it. After the first non- const operator, operations that modify QString may completely (in case of reallocation) or partially invalidate iterators and references, but other methods (such as begin() or end()) will not. Accessing an iterator or reference after it has been invalidated leads to undefined behavior.

A frequent requirement is to remove whitespace characters from a string (‘\n’, ‘\t’, ‘ ‘, etc.). If you want to remove whitespace from both ends of a QString, use the trimmed() function. If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the string, use simplified().

If you want to find all occurrences of a particular character or substring in a QString, use the indexOf() or lastIndexOf() functions. The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here is a typical loop that finds all occurrences of a particular substring:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

To get an upper- or lowercase version of a string use toUpper() or toLower().

Lists of strings are handled by the QStringList class. You can split a string into a list of strings using the split() function, and join a list of strings into a single string with an optional separator using QStringList::join(). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegularExpression using the QStringList::filter() function.

Querying String Data

If you want to see if a QString starts or ends with a particular substring use startsWith() or endsWith(). If you simply want to check whether a QString contains a particular character or substring, use the contains() function. If you want to find out how many times a particular character or substring occurs in the string, use count().

To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the QChar data. The pointer is guaranteed to remain valid until a non- const function is called on the QString.

Comparing Strings

QStrings can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. Note that the comparison is based exclusively on the numeric Unicode values of the characters. It is very fast, but is not what a human would expect; the QString::localeAwareCompare() function is usually a better choice for sorting user-interface strings, when such a comparison is available.

On Unix-like platforms (including Linux, macOS and iOS), when Qt is linked with the ICU library (which it usually is), its locale-aware sorting is used. Otherwise, on macOS and iOS, localeAwareCompare() compares according the «Order for sorted lists» setting in the International preferences panel. On other Unix-like systems without ICU, the comparison falls back to the system library’s strcoll() ,

Converting Between Encoded Strings Data and QString

QString provides the following three functions that return a const char * version of the string as QByteArray: toUtf8(), toLatin1(), and toLocal8Bit().

    () returns a Latin-1 (ISO 8859-1) encoded 8-bit string. () returns a UTF-8 encoded 8-bit string. UTF-8 is a superset of US-ASCII (ANSI X3.4-1986) that supports the entire Unicode character set through multibyte sequences. () returns an 8-bit string using the system’s local encoding. This is the same as toUtf8() on Unix systems.

To convert from one of these encodings, QString provides fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through the QStringEncoder and QStringDecoder classes.

As mentioned above, QString provides a lot of functions and operators that make it easy to interoperate with const char * strings. But this functionality is a double-edged sword: It makes QString more convenient to use if all strings are US-ASCII or Latin-1, but there is always the risk that an implicit conversion from or to const char * is done using the wrong 8-bit encoding. To minimize these risks, you can turn off these implicit conversions by defining some of the following preprocessor symbols:

    disables automatic conversions from C string literals and pointers to Unicode. allows automatic conversions from C characters and character arrays, but disables automatic conversions from character pointers to Unicode. disables automatic conversion from QString to C strings.

You then need to explicitly call fromUtf8(), fromLatin1(), or fromLocal8Bit() to construct a QString from an 8-bit string, or use the lightweight QLatin1String class, for example:

Similarly, you must call toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string.

The result variable, is a normal variable allocated on the stack. When return is called, and because we’re returning by value, the copy constructor is called and a copy of the string is returned. No actual copying takes place thanks to the implicit sharing.

Distinction Between Null and Empty Strings

For historical reasons, QString distinguishes between a null string and an empty string. A null string is a string that is initialized using QString’s default constructor or by passing ( const char * )0 to the constructor. An empty string is any string with size 0. A null string is always empty, but an empty string isn’t necessarily null:

All functions except isNull() treat null strings the same as empty strings. For example, toUtf8().constData() returns a valid pointer (not nullptr) to a ‘\0’ character for a null string. We recommend that you always use the isEmpty() function and avoid isNull().

Number Formats

When a QString::arg() ‘%’ format specifier includes the ‘L’ locale qualifier, and the base is ten (its default), the default locale is used. This can be set using QLocale::setDefault(). For more refined control of localized string representations of numbers, see QLocale::toString(). All other number formatting done by QString follows the C locale’s representation of numbers.

When QString::arg() applies left-padding to numbers, the fill character ‘0’ is treated specially. If the number is negative, its minus sign will appear before the zero-padding. If the field is localized, the locale-appropriate zero character is used in place of ‘0’ . For floating-point numbers, this special treatment only applies if the number is finite.

Floating-point Formats

In member functions (e.g., arg(), number()) that represent floating-point numbers ( float or double ) as strings, the form of display can be controlled by a choice of format and precision, whose meanings are as for QLocale::toString(double, char, int).

If the selected format includes an exponent, localized forms follow the locale’s convention on digits in the exponent. For non-localized formatting, the exponent shows its sign and includes at least two digits, left-padding with zero if needed.

More Efficient String Construction

Many strings are known at compile time. But the trivial constructor QString(«Hello»), will copy the contents of the string, treating the contents as Latin-1. To avoid this one can use the QStringLiteral macro to directly create the required data at compile time. Constructing a QString out of the literal does then not cause any overhead at runtime.

A slightly less efficient way is to use QLatin1String. This class wraps a C string literal, precalculates it length at compile time and can then be used for faster comparison with QStrings and conversion to QStrings than a regular C string literal.

Using the QString ‘+’ operator, it is easy to construct a complex string from multiple substrings. You will often write code like this:

There is nothing wrong with either of these string constructions, but there are a few hidden inefficiencies. Beginning with Qt 4.6, you can eliminate them.

First, multiple uses of the ‘+’ operator usually means multiple memory allocations. When concatenating n substrings, where n > 2, there can be as many as n — 1 calls to the memory allocator.

In 4.6, an internal template class QStringBuilder has been added along with a few helper functions. This class is marked internal and does not appear in the documentation, because you aren’t meant to instantiate it in your code. Its use will be automatic, as described below. The class is found in src/corelib/tools/qstringbuilder.cpp if you want to have a look at it.

QStringBuilder uses expression templates and reimplements the ‘%’ operator so that when you use ‘%’ for string concatenation instead of ‘+’ , multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called once to get the required space, and the substrings are copied into it one by one.

Additional efficiency is gained by inlining and reduced reference counting (the QString created from a QStringBuilder typically has a ref count of 1, whereas QString::append() needs an extra test).

There are two ways you can access this improved method of string construction. The straightforward way is to include QStringBuilder wherever you want to use it, and use the ‘%’ operator instead of ‘+’ when concatenating strings:

A more global approach which is the most convenient but not entirely source compatible, is to this define in your .pro file:

and the ‘+’ will automatically be performed as the QStringBuilder ‘%’ everywhere.

Maximum Size and Out-of-memory Conditions

The maximum size of QString depends on the architecture. Most 64-bit systems can allocate more than 2 GB of memory, with a typical limit of 2^63 bytes. The actual value also depends on the overhead required for managing the data block. As a result, you can expect the maximum size of 2 GB minus overhead on 32-bit platforms, and 2^63 bytes minus overhead on 64-bit platforms. The number of elements that can be stored in a QString is this maximum size divided by the size of QChar.

When memory allocation fails, QString throws a std::bad_alloc exception if the application was compiled with exception support. Out of memory conditions in Qt containers are the only case where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.

Note that the operating system may impose further limits on applications holding a lot of allocated memory, especially large, contiguous blocks. Such considerations, the configuration of such behavior or any mitigation are outside the scope of the Qt API.

QString Class

Note: All functions in this class are reentrant.

Public Types

typedef ConstIterator
typedef Iterator
enum NormalizationForm
enum SectionFlag
flags SectionFlags
typedef const_iterator
typedef const_pointer
typedef const_reference
typedef const_reverse_iterator
typedef difference_type
typedef iterator
typedef pointer
typedef reference
typedef reverse_iterator
typedef size_type
typedef value_type

Public Functions

Static Public Members

QString asprintf(const char *cformat, . )
int compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, QLatin1String s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(QLatin1String s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString fromCFString(CFStringRef string)
QString fromLatin1(const char *str, int size = -1)
QString fromLatin1(const QByteArray &str)
QString fromLocal8Bit(const char *str, int size = -1)
QString fromLocal8Bit(const QByteArray &str)
QString fromNSString(const NSString *string)
QString fromRawData(const QChar *unicode, int size)
QString fromStdString(const std::string &str)
QString fromStdU16String(const std::u16string &str)
QString fromStdU32String(const std::u32string &str)
QString fromStdWString(const std::wstring &str)
QString fromUcs4(const uint *unicode, int size = -1)
QString fromUcs4(const char32_t *str, int size = -1)
QString fromUtf8(const char *str, int size = -1)
QString fromUtf8(const QByteArray &str)
QString fromUtf16(const ushort *unicode, int size = -1)
QString fromUtf16(const char16_t *str, int size = -1)
QString fromWCharArray(const wchar_t *string, int size = -1)
int localeAwareCompare(const QString &s1, const QString &s2)
int localeAwareCompare(const QString &s1, const QStringRef &s2)
QString number(long n, int base = 10)
QString number(int n, int base = 10)
QString number(uint n, int base = 10)
QString number(ulong n, int base = 10)
QString number(qlonglong n, int base = 10)
QString number(qulonglong n, int base = 10)
QString number(double n, char format = ‘g’, int precision = 6)
QString vasprintf(const char *cformat, va_list ap)

Related Non-Members

bool operator!=(const QString &s1, const QString &s2)
bool operator!=(const char *s1, const QString &s2)
const QString operator+(const QString &s1, const QString &s2)
const QString operator+(const QString &s1, const char *s2)
const QString operator+(const char *s1, const QString &s2)
const QString operator+(char ch, const QString &s)
const QString operator+(const QString &s, char ch)
bool operator<(const QString &s1, const QString &s2)
bool operator<(const char *s1, const QString &s2)
QDataStream & operator<<(QDataStream &stream, const QString &string)
bool operator<=(const QString &s1, const QString &s2)
bool operator<=(const char *s1, const QString &s2)
bool operator==(const QString &s1, const QString &s2)
bool operator==(const char *s1, const QString &s2)
bool operator>(const QString &s1, const QString &s2)
bool operator>(const char *s1, const QString &s2)
bool operator>=(const QString &s1, const QString &s2)
bool operator>=(const char *s1, const QString &s2)
QDataStream & operator>>(QDataStream &stream, QString &string)

Macros

QStringLiteral(str)
QT_NO_CAST_FROM_ASCII
QT_NO_CAST_TO_ASCII
QT_RESTRICTED_CAST_FROM_ASCII

Detailed Description

QString stores a string of 16-bit QChars, where each QChar corresponds to one UTF-16 code unit. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)

Unicode is an international standard that supports most of the writing systems in use today. It is a superset of US-ASCII (ANSI X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1 characters are available at the same code positions.

Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.

In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit ‘\0’-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application’s market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (like in embedded systems).

Initializing a String

One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello":

QString converts the const char * data into Unicode using the fromUtf8() function.

In all of the QString functions that take const char * parameters, the const char * is interpreted as a classic C-style ‘\0’-terminated string encoded in UTF-8. It is legal for the const char * parameter to be nullptr .

You can also provide string data as an array of QChars:

QString makes a deep copy of the QChar data, so you can modify it later without experiencing side effects. (If for performance reasons you don’t want to take a deep copy of the character data, use QString::fromRawData() instead.)

Another approach is to set the size of the string using resize() and to initialize the data character per character. QString uses 0-based indexes, just like C++ arrays. To access the character at a particular index position, you can use operator[](). On non-const strings, operator[]() returns a reference to a character that can be used on the left side of an assignment. For example:

For read-only access, an alternative syntax is to use the at() function:

The at() function can be faster than operator[](), because it never causes a deep copy to occur. Alternatively, use the left(), right(), or mid() functions to extract several characters at a time.

A QString can embed ‘\0’ characters (QChar::Null). The size() function always returns the size of the whole string, including embedded ‘\0’ characters.

After a call to the resize() function, newly allocated characters have undefined values. To set all the characters in the string to a particular value, use the fill() function.

QString provides dozens of overloads designed to simplify string usage. For example, if you want to compare a QString with a string literal, you can write code like this and it will work as expected:

You can also pass string literals to functions that take QStrings as arguments, invoking the QString(const char *) constructor. Similarly, you can pass a QString to a function that takes a const char * argument using the qPrintable() macro which returns the given QString as a const char * . This is equivalent to calling <QString>.toLocal8Bit().constData().

Manipulating String Data

QString provides the following basic functions for modifying the character data: append(), prepend(), insert(), replace(), and remove(). For example:

If you are building a QString gradually and know in advance approximately how many characters the QString will contain, you can call reserve(), asking QString to preallocate a certain amount of memory. You can also call capacity() to find out how much memory QString actually allocated.

The replace() and remove() functions’ first two arguments are the position from which to start erasing and the number of characters that should be erased. If you want to replace all occurrences of a particular substring with another, use one of the two-parameter replace() overloads.

A frequent requirement is to remove whitespace characters from a string (‘\n’, ‘\t’, ‘ ‘, etc.). If you want to remove whitespace from both ends of a QString, use the trimmed() function. If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the string, use simplified().

If you want to find all occurrences of a particular character or substring in a QString, use the indexOf() or lastIndexOf() functions. The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here is a typical loop that finds all occurrences of a particular substring:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

To get an upper- or lowercase version of a string use toUpper() or toLower().

Lists of strings are handled by the QStringList class. You can split a string into a list of strings using the split() function, and join a list of strings into a single string with an optional separator using QStringList::join(). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegExp using the QStringList::filter() function.

Querying String Data

If you want to see if a QString starts or ends with a particular substring use startsWith() or endsWith(). If you simply want to check whether a QString contains a particular character or substring, use the contains() function. If you want to find out how many times a particular character or substring occurs in the string, use count().

To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the QChar data. The pointer is guaranteed to remain valid until a non-const function is called on the QString.

Comparing Strings

QStrings can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. Note that the comparison is based exclusively on the numeric Unicode values of the characters. It is very fast, but is not what a human would expect; the QString::localeAwareCompare() function is usually a better choice for sorting user-interface strings, when such a comparison is available.

On Unix-like platforms (including Linux, macOS and iOS), when Qt is linked with the ICU library (which it usually is), its locale-aware sorting is used. Otherwise, on macOS and iOS, localeAwareCompare() compares according the "Order for sorted lists" setting in the International preferences panel. On other Unix-like systems without ICU, the comparison falls back to the system library’s strcoll() , falling back when it considers strings equal to QString’s (locale-unaware) comparison, described above,

Converting Between 8-Bit Strings and Unicode Strings

QString provides the following three functions that return a const char * version of the string as QByteArray: toUtf8(), toLatin1(), and toLocal8Bit().

    () returns a Latin-1 (ISO 8859-1) encoded 8-bit string. () returns a UTF-8 encoded 8-bit string. UTF-8 is a superset of US-ASCII (ANSI X3.4-1986) that supports the entire Unicode character set through multibyte sequences. () returns an 8-bit string using the system’s local encoding.

To convert from one of these encodings, QString provides fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through the QTextCodec class.

As mentioned above, QString provides a lot of functions and operators that make it easy to interoperate with const char * strings. But this functionality is a double-edged sword: It makes QString more convenient to use if all strings are US-ASCII or Latin-1, but there is always the risk that an implicit conversion from or to const char * is done using the wrong 8-bit encoding. To minimize these risks, you can turn off these implicit conversions by defining the following two preprocessor symbols:

  • QT_NO_CAST_FROM_ASCII disables automatic conversions from C string literals and pointers to Unicode.
  • QT_RESTRICTED_CAST_FROM_ASCII allows automatic conversions from C characters and character arrays, but disables automatic conversions from character pointers to Unicode.
  • QT_NO_CAST_TO_ASCII disables automatic conversion from QString to C strings.

One way to define these preprocessor symbols globally for your application is to add the following entry to your qmake project file:

You then need to explicitly call fromUtf8(), fromLatin1(), or fromLocal8Bit() to construct a QString from an 8-bit string, or use the lightweight QLatin1String class, for example:

Similarly, you must call toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string. (Other encodings are supported through the QTextCodec class.)

The result variable, is a normal variable allocated on the stack. When return is called, and because we’re returning by value, the copy constructor is called and a copy of the string is returned. No actual copying takes place thanks to the implicit sharing.

Distinction Between Null and Empty Strings

For historical reasons, QString distinguishes between a null string and an empty string. A null string is a string that is initialized using QString’s default constructor or by passing (const char *)0 to the constructor. An empty string is any string with size 0. A null string is always empty, but an empty string isn’t necessarily null:

All functions except isNull() treat null strings the same as empty strings. For example, toUtf8().constData() returns a valid pointer (not nullptr) to a ‘\0’ character for a null string. We recommend that you always use the isEmpty() function and avoid isNull().

Argument Formats

In member functions where an argument format can be specified (e.g., arg(), number()), the argument format can be one of the following:

Format Meaning
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g use e or f format, whichever is the most concise
G use E or f format, whichever is the most concise

A precision is also specified with the argument format. For the ‘e’, ‘E’, and ‘f’ formats, the precision represents the number of digits after the decimal point. For the ‘g’ and ‘G’ formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).

More Efficient String Construction

Many strings are known at compile time. But the trivial constructor QString("Hello"), will copy the contents of the string, treating the contents as Latin-1. To avoid this one can use the QStringLiteral macro to directly create the required data at compile time. Constructing a QString out of the literal does then not cause any overhead at runtime.

A slightly less efficient way is to use QLatin1String. This class wraps a C string literal, precalculates it length at compile time and can then be used for faster comparison with QStrings and conversion to QStrings than a regular C string literal.

Using the QString ‘+’ operator, it is easy to construct a complex string from multiple substrings. You will often write code like this:

There is nothing wrong with either of these string constructions, but there are a few hidden inefficiencies. Beginning with Qt 4.6, you can eliminate them.

First, multiple uses of the ‘+’ operator usually means multiple memory allocations. When concatenating n substrings, where n > 2, there can be as many as n — 1 calls to the memory allocator.

In 4.6, an internal template class QStringBuilder has been added along with a few helper functions. This class is marked internal and does not appear in the documentation, because you aren’t meant to instantiate it in your code. Its use will be automatic, as described below. The class is found in src/corelib/tools/qstringbuilder.cpp if you want to have a look at it.

QStringBuilder uses expression templates and reimplements the ‘%’ operator so that when you use ‘%’ for string concatenation instead of ‘+’ , multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called once to get the required space, and the substrings are copied into it one by one.

Additional efficiency is gained by inlining and reduced reference counting (the QString created from a QStringBuilder typically has a ref count of 1, whereas QString::append() needs an extra test).

There are two ways you can access this improved method of string construction. The straightforward way is to include QStringBuilder wherever you want to use it, and use the ‘%’ operator instead of ‘+’ when concatenating strings:

A more global approach which is the most convenient but not entirely source compatible, is to this define in your .pro file:

and the ‘+’ will automatically be performed as the QStringBuilder ‘%’ everywhere.

Maximum size and out-of-memory conditions

The current version of QString is limited to just under 2 GB (2^31 bytes) in size. The exact value is architecture-dependent, since it depends on the overhead required for managing the data block, but is no more than 32 bytes. Raw data blocks are also limited by the use of int type in the current version to 2 GB minus 1 byte. Since QString uses two bytes per character, that translates to just under 2^30 characters in one QString.

In case memory allocation fails, QString will throw a std::bad_alloc exception. Out of memory conditions in the Qt containers are the only case where Qt will throw exceptions.

Note that the operating system may impose further limits on applications holding a lot of allocated memory, especially large, contiguous blocks. Such considerations, the configuration of such behavior or any mitigation are outside the scope of the Qt API.

Qt: записать структуру в файл

Я борюсь с написанием struct в файл через QFile в Qt.

DataPacket структура заполняется в другом месте:

Когда я проверяю outputFile файл журнала, $GPGSA. Строка не где увидеть. Если я тогда дополнительно напишу payload поле отдельно:

$GPGSA Строка впоследствии написана правильно.

Я что-то упустил …

Решение

Другое дело, что для обеспечения совместимости с Qt переименуйте некоторые нативные типы, поэтому я рекомендую использовать эквивалентные типы, в дополнение к прямому использованию QString вместо char * payload и payloadLength, как показано ниже:

Также при написании лучше использовать QDataStream как показано ниже:

В следующем примере показано его использование:

Замечания: QDataStream устанавливает payloadLength косвенно, потому что он знает размер QString.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *