QT常见问题和解决方案整理

 最近重拾QT,发现百度能搜索到的东西甚少,所以上StackOverFlow上查了一些资料,觉得对自己有用的就做了记录,方便以后查看,本篇基于Qt4.8.5,windows平台。

 问题1. 如何将整数型转成QString

 链接https://stackoverflow.com/questions/3211771/how-to-convert-int-to-qstring

    解决方法

    使用 QString::number()方法

 1 int i = 42; 2 QString s = QString::number(i); 

     如果你需要将数字放入字符串里面,建议这样写:

1 int i = 42;   
2 QString printable = QString::fromLatin1("数字是 %1. ").arg(i);

 问题2 如何将QString转成string

 链接https://stackoverflow.com/questions/4214369/how-to-convert-qstring-to-stdstring

 解决方法

1 QString qs;
2 // do things
3 qDeubug() << qs.toStdString();

 如果不考虑特殊字符的话,直接使用QString::toStdString()是没有问题的,并且在Qt5.0以后QString::toStdString()会使用QString::toUtf8()来进行转换;

 但是考虑编码问题的话,比如你的字符串是这样的QString s = QString::fromUtf8("árvíztűrő tükörfúrógép ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"),建议使用:

1 QString qs;
2 
3 string current_locale_text = qs.toLocal8Bit().constData();

问题3  如何将string转QString

链接:https://stackoverflow.com/questions/1814189/how-to-change-string-into-qstring

解决方法:

如果是std::string 可以使用如下方法:

1 std::string str = "Hello world";
2 QString qstr = QString::fromStdString(str);

 

如果是Ascii编码的Const char*使用如下方法:

 

const char* str = "Hello world";
QString qstr = QString::fromAscii(str);

 

 

如果是系统编码且可以被QTextCodec::codecForLocale()读的Const char*使用如下方法:

1 const char* str = "zażółć gęślą jaźń";      // latin2 source file and system encoding
2 QString qstr = QString::fromLocal8Bit(str);

 

如果是Utf-8编码的Const char*使用如下方法:

1 const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
2 QString qstr = QString::fromUtf8(str);

 

QT也支持Utf-16编码的Const ushort*,使用如下方法:

1 const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
2 QString qstr = QString::fromUtf16(str);

 

 

问题4 Qt容器和STL容器的选择

 链接:https://stackoverflow.com/questions/1668259/stl-or-qt-containers

答案中提到了很多Qt容器的优点,比如更多的功能,STL风格和Java风格的遍历方式,更可靠、稳定的实现,更少的占用内存等等,个人感觉Qt容器的优势是简单、安全、轻量级,比较赞同第二高赞的回答:

This is a difficult to answer question. It can really boil down to a philosophical/subjective argument.

That being said...

I recommend the rule "When in Rome... Do as the Romans Do"

Which means if you are in Qt land, code as the Qt'ians do. This is not just for readability/consistency concerns. 
Consider what happens if you store everything in a stl container then you have to pass all that data over to a Qt function.
Do you really want to manage a bunch of code that copies things into/out-of Qt containers. Your code is already heavily dependent on Qt,
so its not like you
're making it any more "standard" by using stl containers.
And whats the point of a container if everytime you want to use it for anything useful, you have to copy it out into the corresponding Qt container?


渣译如下:

入乡随俗。如果你使用Qt平台,就尽量使用带有Qt特性的容器,这不仅仅是出于稳定性/一致性的考虑。试想一下如果你将所有的数据都存储在Stl容器内然后你想把他们传给一个Qt方法那有多糟糕(其实没他说的那么可怕)。你真的想要将东西拷来拷去吗?如果你的工程已经重度依赖Qt了,那么仅仅为了标准去使用stl容器,就没有意义了。

问题5:检查一个文件夹是否存在

链接:https://stackoverflow.com/questions/2241808/checking-if-a-folder-exists-and-creating-folders-in-qt-c

解决方法:

检查文件夹是否存在:

QDir("Folder").exists();

创建一个新的文件夹:

QDir().mkdir("Folder");

检查一个文件夹是否存在不存在则创建此文件夹,可以这样写:

1 QDir dir("Folder");
2 if (!dir.exists()) {
3     dir.mkpath(".");
4 }

 

问题6:Q_OBJECT宏的作用是什么?为什么所有的QT对象都要声明这个宏?

链接:https://stackoverflow.com/questions/1368584/what-does-the-q-object-macro-do-why-do-all-qt-objects-need-this-macro#comment60582957_12099467

解决方法:

高票答案原文:

From the Qt documentation:
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file.If it finds one or more class declarations that contain the Q_OBJECT macro, 
it produces a C++ source file containing the meta-object code for those classes. 
Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

 渣译:

Moc工具会读取C++头文件,如果它发现一个或者多个类的声明中有Q_OBJECT宏,它会产生一个包含元对象代码的C++源文件。除此以外,元对象代码对于信号槽机制、运行时类型信息,动态属性系统来说都是必不可少的。

 

问题7:Qt的内存管理

链接:https://stackoverflow.com/questions/2491707/memory-management-in-qt

解决方法:

高票答案原文:

If you build your own hierarchy with QObjects, that is, you initialise all newly created QObjects with a parent,
QObject* parent = new QObject();
QObject* child = new QObject(parent);
then it is enough to delete the parent, because the parents destructor will take care of destroying child. (It does this by issuing signals, so it is safe even when you delete childmanually before the parent.)
You could also delete the child first, the order doesn't matter. For an example where the order doesmatter here's the documentation about object trees.
If your MyClass is not a child of QObject, you’ll have to use the plain C++ way of doing things.
Also, note that the parent–child hierarchy of QObjects is generally independent of the hierarchy of the C++ class hierarchy/inheritance tree. That means, that an assigned child does not need to be a direct subclass of it’s parent. 
Any (subclass of) QObject will suffice. There might be some constraints imposed by the constructors
for other reasons, however; such as in QWidget(QWidget* parent=0), where the parent must be another QWidget, due to e.g. visibility flags and because you’d do some basic layout that way;
but for Qt's hierarchy system in general, you are allowed to have any QObject as a parent.

 

渣译:

如果你建立对象层级关系的时候都是使用QObjects的话,像这样:
那么删除掉父级对象足以,因为父级对象的析构器会处理自己对象的析构(通过发信号的方式),即使你在父级对象析构前删除了子级对象,子类会告诉父类忘了它(forget it);
你可以先将子级对象删除,这里是一个说明顺序是无关的例子http://doc.qt.io/qt-5/objecttrees.html
如果你的类不是一个QObject的子类,你需要按照C
++的方式来进行处理。
QT的父子层级关系是独立于C
++的层级/继承树的。所以即使一个子类不是父类的直接子类,也没关系,只要他是一个QObject就行。

 

posted @ 2017-12-17 13:47  MasterWuGUI  阅读(656)  评论(0编辑  收藏  举报