1、 新建一个Qt GUI应用,并且使Qt自动为我们实现这个GUI应用:菜单栏->新建文件或项目->应用程序->Qt Gui应用->输入项目名称和所在路径->选择默认构建套件->设置主界面类名及其基类(可以从三种基类之一继承:QMainWindow,QWidget,QDialog)->设置项目管理和版本控制->完成。
这时候我们构建并运行程序就可以看到显示了一个对话框。接着我们通过双击.ui界面文件来进入界面设计模式,从部件列表中拖动一个Label部件到主设计区,并编辑Label显示内容为"hello world! 你好,世界!",还可以在部件的属性栏设置Label的名称、位置、大小等属性。然后再次构建运行程序,可以看到对话框上有了我们添加的Label部件,且Label上显示的是我们刚才设置的文字内容。在这个项目中,Qt自动为我们生成和实现了对话框的头文件和源文件、main函数、.ui文件。
2、新建一个空的Qt项目,通过我们自己编写全部代码来实现这个GUI应用:在新建项目的时候我们选择其他项目->空的Qt项目,项目创建好后我们为项目添加和实现main函数,代码如下,记得添加头文件<QDebug>来能够调试(qDebug()方法可以向应用程序输出栏输出各种格式,如int、string、QObject(输出对象名)、QObjectList等,如 qDebug() << "get value: " << value;):
#include <QApplication> #include <QDialog> #include <QLabel> #include <QString> #include <QTextCodec> #include <QDebug> int main(int argc, char* argv[]) { QApplication app(argc, argv); QDialog dlg; dlg.resize(300, 400); QLabel label(&dlg); label.move(100, 100); /**********Qt Creator中字符串常量默认使用的是utf8编码**********/ //1、使用QTextCodec::setCodecForCStrings设置QString使用的字符编码,此方法在QT5中已废除 //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); //QString str = "你好hello"; //2、使用QTextCodec::setCodecForTr设置tr函数使用的字符编码, tr方法实际上是用来实现国际化的, //所以这样做实际上是兜了个圈子 //QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); //QString str = QObject::tr("hello你好"); //3、使用QString的from...方法来直接设置QString应该使用的字符编码 QString str = QString::fromUtf8("你hello好"); QString wstr = QString::fromStdWString(L"你好hello"); //4、QTextCodec可以提供两种编码之间的转换,比如下面是将utf8转换为unicode QByteArray encodedString = "hello你好"; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); //使用utf8编码的codec QString ustr = codec->toUnicode(encodedString); QChar*data = ustr.data(); int res = memcmp(data, L"hello你好", sizeof(L"hello你好")); qDebug() << res; //输出为0 //5、QTextCodec::codecForLocale()可以获得最适合本机环境使用的编码,以下是将unicode转换为utf8 QByteArray aryByte = codec->fromUnicode(ustr); res = memcmp(aryByte.data(), "hello你好", sizeof("hello你好")); qDebug() << res; //输出为0 /*********Qt Creator中sizeof字符串得到的大小与VS中不同*********/ qDebug("%d\n", sizeof("ab测试")); //输出为9 qDebug() << sizeof(L"ab测试") << endl; //输出为10 //6、QStringList的使用 QStringList l; l << QString::fromUtf8("item1") << QString::fromUtf8("item2"); for(int i = 0; i < l.size(); i++) qDebug() << l[i] << endl; label.setText(str); dlg.show(); return app.exec(); //进入事件循环 }