Qt 5: const char * QString cast

In Qt 4, you can automatically include a QString in a "const char *", for example. I could pass a QString to a function expecting a "const char *".

void myFunction(const char *parameter);

QString myString;
myFunction(myString); //works in QT4

In Qt 5, however, I would get "error C2440:" cast type ": it is not possible to convert from" QString "to" const char * "(that is, the Visual C ++ 2008 compiler, other compilers will throw something similar). If I I understand the documentation correctly, this is due to the fact that the level of compatibility of Qt 3 is no longer included in QT5.

Of course, I could change the function call from

myFunction(myString); 

to

myFunction(myString.toLatin1().data());

However, I have a huge code base that compiles perfectly with Qt 4, and I would really like my old code to compile with Qt 5 without modifying it. Is there any way to achieve this?

+4
4

, , grep, .

#define QString2charp(myString) myString.toLatin1().data()

inline char* QString2charp (const QString &myString)
{
    return myString.toLatin1().data();
}

:

myFunction(QString2charp(myString));

, , "myFunction" , QString.

void myFunction(const char *parameter);
void myFunction(QString parameter);

:

void myFunction(const QString &parameter)
{
    myFunction(myString.toLatin1().data());
}

, , , , const char*, QString, Qt 5.

, QString, , , . , Qt 5 , .

, - , . , ?

+2

  • MyFunction( const QString & parameter ) (, , char *)
  • MyFunction:

    void myFunction(const char *parameter); //this is your normal function
    void myFunction( const QString & parameter )
    {
        char * c_str = nullptr;
        <convert parameter to char * in any way that suits you>
        myFunction( c_str );
    }
    
  • - , , , , :

    void MyFunctionWrapper( const QString & parameter )
    {
        <same as above>
    }
    
0

QString const char* >= Qt 5, QString UTF-16 ASCII.

- a) , const char*, QString s,
b) -,
c) char, std::string.

.

0

QT

const QByteArray byteArray = mytext = textBox.text().toUtf8();
const char *mytext = byteArray.constData();
0

Source: https://habr.com/ru/post/1540671/


All Articles