Search code examples
c++qtqt-creatorqt6

Qt Creator Error when trying to split a QString


I have a string that I am trying to split on the first instance of the delimiter, in this case "~". These are the calls I am making:

QString line = "hello~world~how~are~you";
QStringList list = line.split("~", Qt::SplitLimit::KeepEmptyParts, Qt::CaseSensitive);

Ideally I would get:

list.at(0); = "hello"  
list.at(1); = "world~how~are~you"

However this throws an error.

.... error: 'Qt::SplitLimit' has not been declared
.... In function 'int qMain(int, char**)':

I am using Qt Creator version 6.4.2 with Microsoft Windows 10 and I am trying to code in C++. I am using the CMake build system. I have included QtCore in the project, so that shouldn't be the issue.

I do not know if this is the best way to split a QString so if anyone has a better suggestion I would gladly try it. In the meantime I think I will just fully split it. Use the first entry, and then re-append the rest together.


Solution

  • The second parameter to split method is of type Qt::SplitBehavior and as mentioned in the comment it is an old fashioned enum not C++11 enum class.

    QStringList QString::split(const QString &sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
    

    So you should use:

    QStringList list = line.split("~", Qt::KeepEmptyParts, Qt::CaseSensitive);
    

    But, QString's split method splits the string into substrings wherever sep occurs, and returns the list of those strings. You can't partially split the string using split method.

    To split only on the first occurrence of delimiter use indexOf method as follows:

    auto idx = line.indexOf('~');
    auto part= line.mid(0, idx);
    auto rest = line.mid(idx+1);
    qDebug() << part;
    qDebug() << rest;
    

    Output:

    "hello"
    "world~how~are~you"