C++ 将 const char* 转换为 QString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20824781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:20:29  来源:igfitidea点击:

Convert const char* to QString

c++qtqstringqtcoreconst-cast

提问by Mahmoud Hassan

I have to use the output of a function of a type const char*and I need to convert it to QString.

我必须使用类型函数的输出,const char*我需要将其转换为QString.

Note: inside that function, these are lines of code to return the const char*

注意:在该函数中,这些是返回 const char*

char* ClassA::getData() const{
    return const_cast<char *> (_foo.c_str());
}

where _foois std::string.

哪里_foostd::string

I tried to use the following lines of code but always get empty string (actually not empty but contain only the new lines characters and neglect all other characters).

我尝试使用以下代码行,但总是得到空字符串(实际上不为空,但只包含新行字符而忽略所有其他字符)。

QString foo1 = QString(temp.getData());
QString foo2 = QString::fromLocal8Bit(temp.getData());
QString foo3 = QString(QLatin1String(temp.getData()));
QString foo4 = QString::fromAscii(temp.getData());
QString foo5 = QString::fromUtf8(temp.getData());

采纳答案by lpapp

The code below should work fine. Your issue is most likely somewhere else. Please do a clean build.

下面的代码应该可以正常工作。您的问题很可能在其他地方。请做一个干净的构建。

The error will be somewhere else in your more complex code that you have not shared with us. You are probably getting issues with setting _foo incorrectly.

错误将出现在您尚未与我们共享的更复杂代码中的其他位置。您可能会遇到错误设置 _foo 的问题。

As you noted yourself, you cannot change the interface, but it is better to take a note that in an ideal world, you would not mix std strings with QStrings. You would just use QStrings altogether in your code.

正如您自己指出的那样,您无法更改界面,但最好注意,在理想情况下,您不会将 std 字符串与 QString 混合使用。您只需在代码中完全使用 QStrings 即可。

Even if you need to use std or raw char* types for some reason, it is better not to do such a const cast in the code since QString will cope with const strings passed to it.

即使出于某种原因需要使用 std 或原始 char* 类型,最好不要在代码中进行这样的 const 转换,因为 QString 将处理传递给它的 const 字符串。

main.cpp

主程序

#include <QString>
#include <QDebug>

class ClassA
{
    public:
        ClassA() { _foo = "Hello World!\n"; }
        ~ClassA() {}

        char* getData() const {
            return const_cast<char *> (_foo.c_str());
        }

    private:
        std::string _foo;
};

int main()
{
    ClassA temp;
    QString myString = QString::fromUtf8(temp.getData());
    qDebug() << "TEST:" << myString;
    return 0;
}

main.pro

主程序

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Output

输出

TEST: "Hello World!
"