문제

I have QT_NO_CAST_FROM_ASCII defined so I cannot cast from a char* to a QString. Previously I've been using: QLatin1String
But I just noticed QString::fromStdString, I don't like using this because QLatin1String is preferred to QString::fromLatin1.

Does anyone know of a Qt object for std::strings that works like QLatin1String?

도움이 되었습니까?

해결책

For those who use Qt with QT_NO_CAST_FROM_ASCII enabled char*s and std::strings cannot be assigned to a QString or cast to a QString.

This will not compile with QT_NO_CAST_FROM_ASCII enabled:

QString foo( "Hello World" );

You could do this but Qt frowns upon it because it creates, "temporary QString objects and make a deep copy of the character data":

QString foo( QString::fromLatin1( "Hello World" ) );

Instead you have to use:

QString foo( QLatin1String( "Hello World" ) );

It's a little more frustrating if you need to get a QString from a std::string because you have to now call:

QString foo( QLatin1String( helloWorld.c_str() ) );

There is a direct conversion but not with Qt's recommended wrappers:

QString foo( QString::fromStdString( helloWorld ) );

That is to say I have not been able to find a wrapper for std::string and JKSH asserts that there isn't one. So I believe that as of Qt 5.2 the preferred solution is to use the QLatin1String wrapper.



(As an aside for those interested in multilingual software, Qt's QLatin1String and QString::fromLaint1 both expect the char* to be in proper unicode; QString::fromStdString actually uses QString::fromUtf8 under the hood to convert to proper unicode.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top