一、簡介
QT的一些知識點總結,友善以後查閱。
二、詳解
1、擷取螢幕的工作區的大小
{
//擷取螢幕分辨率
qDebug()<< "screen width:"<<QApplication::desktop()->width();
qDebug()<< "screen height:"<<QApplication::desktop()->height();
//下面方法也可以
qDebug()<< "screen width:"<<qApp->desktop()->width();
qDebug()<< "screen height:"<<qApp->desktop()->height();
//擷取客戶使用區大小
qDebug()<< "screen avaliabe width:"<<QApplication::desktop()->availableGeometry().width();
qDebug()<< "screen avaliabe heigth:"<<QApplication::desktop()->availableGeometry().height();
//擷取應用程式矩形大小
qDebug()<< "application avaliabe width:"<<QApplication::desktop()->screenGeometry().width();
qDebug()<< "application avaliabe heigth:"<<QApplication::desktop()->screenGeometry().height();
}
移動到視窗中央:
move((QApplication::desktop()->width() - width())/2, (QApplication::desktop()->height() - height())/2);
全屏設定:
setWindowState(Qt::WindowFullScreen);
2、設定應用程式圖示
{
QIcon icon;
icon.addPixmap(QPixmap(QString::fromUtf8(":/images/logo.png")), QIcon::Normal, QIcon::Off);
win->setWindowIcon(icon);
win->setIconSize(QSize(256, 256));
}
3、顯示圖檔Label
{
QLabel *logoLabel;
logoLabel = new QLabel();
logoLabel->setObjectName(QString::fromUtf8("logolabel"));
logoLabel->setGeometry(QRect(160, 110, 128, 128));
logoLabel->setPixmap(QPixmap(QString::fromUtf8(":/images/logo.png")));
logoLabel->setScaledContents(true);
}
4、字型更改
{
QFont font;
font.setPointSize(40);
font.setBold(true);
font.setWeight(75);
QLabel *fontLabel = new QLabel();
fontLabel->setFont(font);
}
5、文本顔色更改
void Widget::changeColor(QWidget *window, QColor color)
{
QPalette *palette = new QPalette();
palette->setColor(QPalette::Text, color);
window->setPalette(*palette);
delete palette;
}
6、時間日期轉QString
QString date_str = QDate::currentDate().toString(QString("yyyyMMdd")); //"yyyyMMdd"為轉換格式,該格式轉換後日期如"20121205"
QString time_str = QTime::currentTime().toString(QString("hhmmss")); //"hhmmss"為轉換格式,該格式轉換後時間如"080359"
7、Qt界面風格
qApp>setStyle(new QPlastiqueStyle); //在window中main函數中使用這句話會讓界面快速的變得好看。
8、qobject_cast用法
函數原型:
T qobject_cast (QObject * object)
該方法傳回object向下的轉型T,如果轉型不成功則傳回0,如果傳入的object本身就是0則傳回0。
使用場景:
當某一個Object emit一個signal的時候(即sender),系統會記錄下目前是誰emit出這個signal的,是以在對應的slot裡就可以通過 sender()得到目前是誰invoke了slot。有可能多個 Object的signal會連接配接到同一個signal(例如多個Button可能會connect到一個slot函數onClick()),是以這是就需要判斷到底是哪個Object emit了這個signal,根據sender的不同來進行不同的處理.
在槽函數中:
QPushButton *button_tmp = qobject_cast<QPushButton *>(sender()); //信号的對象,向下轉型為按鈕類型
9、Qslider進入顯示
{
slider = new QSlider;
slider->setRange(0,100);
slider->setTickInterval(10);
slider->setOrientation(Qt::Horizontal);
slider->setValue(100);
slider->setVisible(false);
connect(slider,SIGNAL(valueChanged(int)),this,SLOT(slotChanged(int)));
}
void PicTrans::enterEvent ( QEvent * )
{
slider->setVisible(true);
}
void PicTrans::leaveEvent(QEvent *)
{
slider->setVisible(false);
}
進入slider顯示,離開slider隐藏。
10、Qt不重複随機數
{ //qt
QTime time; time= QTime::currentTime();
qsrand(time.msec()+time.second()*1000);
qDebug() << qrand() % 100; //在0-100中産生出随機數
}
{ //c語言
srand(unsigned(time(0)));
int number = rand() % 100; /*産生100以内的随機整數*/
}
11、QSettings儲存視窗狀态
void
Settings::readSettings()
{
QSettings setting("MyPro","settings");
setting.beginGroup("Dialog");
QPoint pos = setting.value("position").toPoint();
QSize size = setting.value("size").toSize();
setting.endGroup();
setting.beginGroup("Content");
QColor color = setting.value("color").value<QColor>();
QString text = setting.value("text").toString();
setting.endGroup();
move(pos);
resize(size);
QPalette p = label->palette();
p.setColor(QPalette::Normal,QPalette::WindowText,color);
label->setPalette(p);
edit->setPlainText(text);
}
void
Settings::writeSettings()
{
QSettings setting("MyPro","settings");
setting.beginGroup("Dialog");
setting.setValue("position",pos());
setting.setValue("size",size());
setting.endGroup();
setting.beginGroup("Content");
setting.setValue("color",label->palette().color(QPalette::WindowText));
setting.setValue("text",edit->toPlainText());
setting.endGroup();
}
12、兩個信号連接配接同一個槽
參考上述的例8。
connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(slotClick()));
connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(slotClick()));
void Dialog::slotClick()
{
QPushButton* btn = dynamic_cast<QPushButton*>(sender());
if (btn == ui->btn_ok) {
qDebug() << "button:" <<ui->btn_ok->text();
}
else if (btn == ui->btn_cancel) {
qDebug() << "button:" <<ui->btn_cancel->text();
}
}
有時button類型不同時,可以分别判斷對象指針。
void Dialog::slotClick()
{
;
if ((QPushButton* btn = dynamic_cast<QPushButton*>(sender())) == ui->btn_ok) {
qDebug() << "button:" <<ui->btn_ok->text();
}
else if ((QRadioButton* btn = dynamic_cast<QRadioButton*>(sender())) == ui->btn_cancel) {
qDebug() << "button:" <<ui->btn_cancel->text();
}
}
13、對話框操作
視圖模型中, 設定視圖不可編輯 setEditTriggers(QAbstractItemView::NoEditTriggers);
對話框去掉右上角的問号: setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint);
對話框加上最小化按鈕: setWindowFlags(windowFlags()|Qt::WindowMinimizeButtonHint);
14、多語言國際化
1.pro工程檔案裡面添加 TRANSLATIONS+=mypro.ts
2.選擇Qt Creator環境的菜單欄 工具->外部->Qt語言家->更新翻譯(或lupdate mypro.pro或lupdate-qt4mypro.pro)
3.桌面開始菜單裡面Qt目錄打開 Linguist工具
4.Linguist工具加載生成好的mypro.ts檔案
5.填好翻譯, 儲存, Release, 就生成好編譯後的qm檔案
6.在工程的源檔案中, 這樣加載qm檔案:
QTranslator translator;
QLocale locale;
if(QLocale::Chinese == locale.language())
{//中文環境
translator.load("mypro.qm"); //中文
a.installTranslator(&translator);
}//否則預設用英文
15、item-view控件多選後删除
setSelectionMode(QAbstractItemView::MultiSelection); //不按ctrl鍵即可多選
setSelectionMode(QAbstractItemView::ExtendedSelection); //按ctrl鍵多選
QModelIndexList indexList = ui->listvFiles->selectionModel()->selectedRows();
QModelIndex index;
int i = 0;
foreach(index, indexList)
{
this->modFileLists.removeRow(index.row() - i);
++i;
}
16、QByteArray存入中文時亂碼
QByteArray bytes;
bytes.append(this->modFileLists.data(this->modFileLists.index(i), Qt::DisplayRole).toString()); //亂碼
QByteArray bytes;
bytes.append(this->modFileLists.data(this->modFileLists.index(i), Qt::DisplayRole).toString().toLocal8Bit()); //正常
17、Qt托盤
//使用QSystemTrayIcon類
QSystemTrayIcon *tray; //托盤
QMenu *meuTray; //托盤菜單
QAction *acTrayQuit; //托盤退出
this->tray = new QSystemTrayIcon(this);
this->meuTray = new QMenu(this);
this->acTrayQuit = this->meuTray->addAction(QIcon(":/res/image/quit.png"), tr("Quit"));
connect(this->acTrayQuit, SIGNAL(triggered()), this, SLOT(OnExit()));
this->tray->setContextMenu(this->meuTray);
this->tray->setIcon(QIcon(":/res/image/tray.ico"));
this->tray->show();
connect(this->tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(OnTrayActivated(QSystemTrayIcon::ActivationReason)));
voidUpdateTerminal::OnTrayActivated(QSystemTrayIcon::ActivationReasonreason)
{
switch(reason)
{
caseQSystemTrayIcon::DoubleClick:
if(this->isHidden())
this->show();
break;
}
}
18、Qt遞歸周遊檔案和檔案夾
//遞歸周遊檔案夾,找到所有的檔案
//_filePath:要周遊的檔案夾的檔案名
int FindFile(const QString& _filePath)
{
QDir dir(_filePath);
if (!dir.exists()) {
return -1;
}
//取到所有的檔案和檔案名,但是去掉.和..的檔案夾(這是QT預設有的)
dir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
//檔案夾優先
dir.setSorting(QDir::DirsFirst);
//轉化成一個list
QFileInfoList list = dir.entryInfoList();
if(list.size()< 1 ) {
return -1;
}
int i=0;
//遞歸算法的核心部分
do{
QFileInfo fileInfo = list.at(i);
//如果是檔案夾,遞歸
bool bisDir = fileInfo.isDir();
if(bisDir) {
FindFile(fileInfo.filePath());
}
else{
//bool isDll = fileInfo.fileName().endsWith(".dll");
qDebug() << fileInfo.filePath() << ":" <<fileInfo.fileName();
}//end else
i++;
} while(i < list.size());
}
若隻想擷取檔案名,也可以這樣使用:
int FindFile(const QString& _filePath)
{
QDir dir(_filePath);
if (!dir.exists()) {
return -1;
}
//取到所有的檔案和檔案名,但是去掉.和..的檔案夾(這是QT預設有的)
dir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
//檔案夾優先
dir.setSorting(QDir::DirsFirst);
//轉化成一個list
QFileInfoList list = dir.entryInfoList();
QStringList infolist = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
if(list.size()< 1 ) {
return -1;
}
int i=0;
//遞歸算法的核心部分
do{
QFileInfo fileInfo = list.at(i);
//如果是檔案夾,遞歸
bool bisDir = fileInfo.isDir();
if(bisDir) {
FindFile(fileInfo.filePath());
}
else{
for(int m = 0; m <infolist.size(); m++) {
//這裡是擷取目前要處理的檔案名
qDebug() << infolist.at(m);
}
break;
}//end else
i++;
} while(i < list.size());
}
19、Qt調用外部程式QProcess
(1)使用startDetached或execute
使用QProcess類靜态函數QProcess::startDetached(const QString &program, constQStringList &argument)或者QProcess::execute(const QString &program, const QStringList &argument);startDetached 函數不會阻止程序, execute會阻止,即等到這個外部程式運作結束才繼續執行本程序。
例如執行:Shutdown.exe -t -s 3600
QStringList list;
list<< "-t" << "--s" << "3600";
QProcess::startDetached("Shutdown.exe",list);
// QProcess::execute("Shutdown.exe",list);
(2)建立QProcess,使用start函數
可以檢視外部程式傳回的資料,輸出結果。
QProcess *pProces = new QProcess(this);
connect(pProces, SIGNAL(readyRead()),this, SLOT(on_read()));
QStringList list;
pProces->start("Shutdown.exe", list);
void on_read()
{
QProcess *pProces = (QProcess *)sender();
QString result = pProces->readAll();
QMessageBox::warning(NULL, "", result);
}
(3)執行的是程式,如route、ipconfig
QProcess p(0);
p.start("route");
p.waitForStarted();
p.waitForFinished();
qDebug()<<QString::fromLocal8Bit(p.readAllStandardError());
QProcess p(0);
p.start("ipconfig");
p.waitForStarted();
p.waitForFinished();
qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());
(4)執行的是指令,如dir
QProcess p(0);
p.start("cmd");
p.waitForStarted();
p.write("dir\n");
p.closeWriteChannel();
p.waitForFinished();
qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());
或者:
QProcess p(0);
p.start("cmd", QStringList()<<"/c"<<"dir");
p.waitForStarted();
p.waitForFinished();
qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());
(5)QProcess使用管道(指令中不支援管道符|)
一個程序的标準輸出流到目标程序的标準輸入:command1 | command2。
QProcess process1;
QProcess process2;
process1.setStandardOutputProcess(&process2);
process1.start("command1");
process2.start("command2");
20、目前系統Qt所支援的字型
系統支援的所有字型的名稱
QFontDatabase database;
foreach (QString strFamily, database.families()) {
qDebug() <<"family:" << strFamily;
foreach (QString strStyle, database.styles(strFamily)) {
qDebug() << "-----style:" << strStyle;
}
}
系統中所有支援中文的字型名稱
QFontDatabase database;
foreach (const QString &family, database.families(QFontDatabase::SimplifiedChinese))
{
qDebug()<<family;
}
中文亂碼:
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
21、IP正則比對
{
/**********judge ip**********/
QRegExp regExp("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
if(!regExp.exactMatch(ip)) {
flag = false;
ipAddressLineEdit->clear();
ipAddressLineEdit->setError(true);
ipAddressLineEdit->setHint(tr(" IpAddress is wrong"));
}
else flag = true;
}
22、QPushButton去掉虛線框
QPushButton:focus{padding: -1;}
/*
{border-style:flat;} //扁平
button->setFlat(true)
ui->checkBox->setFocusPolicy(Qt::NoFocus);
ui->radioButton->setFocusPolicy(Qt::NoFocus);
*/
23、Qt臨時獲得root權限
(1)getuid()函數傳回一個調用程式的真實使用者ID,使用root執行程式時getuid()傳回值為0。
if (getuid() != 0)
{
QMessageBox::information(0, QString(QObject::tr("Warnning")),
QString(QObject::tr("do not use root privage")),
QString(QObject::tr("OK")));
return -1;
}
(2)臨時獲得root權限
使用getuid()/setuid()函數,讓程式臨時獲得root權限代碼。
/*
* gcc -g -o test-uid test-uid.c
* chown root.root ./test-uid
* chmod 4755 ./test-uid
* ls -al /var
* */
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(int argc, char **argv)
{
// save user uid
uid_t uid = getuid();
// get root authorities
if(setuid(0)) {
printf("test-uid: setuid error");
return -1;
}
printf("test-uid: run as root, setuid is 0\n");
system ("touch /var/testroot");
// rollback user authorities
if(setuid(uid)) {
printf("test-uid: setuid error");
return -1;
}
printf("test-uid: run as user, setuid is %d\n", uid);
system ("touch /var/testuser");
return 0;
}
24、Qt視窗的透明度設定
(1)設定窗體的背景色
在構造函數裡添加代碼,需要添加頭檔案qpalette或qgui
QPalette pal = palette();
pal.setColor(QPalette::Background, QColor(0x00,0xff,0x00,0x00));
setPalette(pal);
通過設定窗體的背景色來實作,将背景色設定為全透。
效果:視窗整體透明,但視窗控件不透明,QLabel控件隻是字顯示,控件背景色透明;窗體客戶區完全透明。
(2)在MainWindow視窗的構造函數中使用如下代碼:
this->setAttribute(Qt::WA_TranslucentBackground, true);
效果:視窗變透明,label也變透明,看不到文字,但是其它控件類似textEdit、comboBox就不會透明,實作了視窗背景透明。
(3)在MainWindow視窗的構造函數中使用如下代碼
this->setWindowOpacity(level);其中level的值可以在0.0~1.0中變化。
效果:視窗變成透明的,但是所有控件也是一樣變成透明。
(4)視窗整體不透明,局部透明:
在Paint事件中使用Clear模式繪圖。
void TestWindow::paintEvent( QPaintEvent* )
{
QPainter p(this);
p.setCompositionMode( QPainter::CompositionMode_Clear );
p.fillRect( 10, 10, 300, 300, Qt::SolidPattern );
}
效果:繪制區域全透明。如果繪制區域有控件不會影響控件
25、Qt解決中文亂碼
在Windows下常使用的是GBK編碼,Linux下常使用的是utf-8編。
選一下任意試試:
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF8"));
//擷取系統編碼,否則移植會出現亂碼
QTextCodec*codec = QTextCodec::codecForName("System");
//設定和對本地檔案系統讀寫時候的預設編碼格式
QTextCodec::setCodecForLocale(codec);
//設定傳給tr函數時的預設字元串編碼
QTextCodec::setCodecForTr(codec);
//用在字元常量或者QByteArray構造QString對象時使用的一種編碼方式
QTextCodec::setCodecForCStrings(codec);
支援linux單一系統時:
QTextCodec *codec = QTextCodec::codecForName("utf8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
26、圖檔做背景縮放
QPixmap backGroundPix = QPixmap(":/resources/images/login.png");
QMatrix martix;
martix.scale(0.95, 0.9);
backGroundPix = backGroundPix.transformed(martix);
resize(backGroundPix.width(), backGroundPix.height());
QPalette palette;
palette.setBrush(QPalette::Window,QBrush(backGroundPix));
setPalette(palette);
或者:
QPixmap backGroundPix;
backGroundPix.load(":/resources/images/login.png");
setAutoFillBackground(true); // 這個屬性一定要設定
QPalette pal(palette());
pal.setBrush(QPalette::Window, QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio, \
Qt::SmoothTransformation)));
setPalette(pal);
27、Qt之界面出現、消失動畫效果
(1)界面出現
将下面這段代碼放在界面的構造函數當中就行
//界面動畫,改變透明度的方式出現0 - 1漸變
QPropertyAnimation *animation = newQPropertyAnimation(this, "windowOpacity");
animation->setDuration(1000);
animation->setStartValue(0);
animation->setEndValue(1);
animation->start();
(2)界面消失:
既然是界面消失,應當是按下關閉按鈕時界面消失,如下:
//連接配接關閉按鈕信号和槽
QObject::connect(close_button, SIGNAL(clicked()), this,SLOT(closeWidget()));
//槽函數如下,主要進行界面透明度的改變,完成之後連接配接槽close來調用closeEvent事件
bool LoginDialog::closeWidget()
{
//界面動畫,改變透明度的方式消失1 - 0漸變
QPropertyAnimation *animation= new QPropertyAnimation(this, "windowOpacity");
animation->setDuration(1000);
animation->setStartValue(1);
animation->setEndValue(0);
animation->start();
connect(animation,SIGNAL(finished()), this, SLOT(close()));
return true;
}
void LoginDialog::closeEvent(QCloseEvent *)
{
//退出系統
QApplication::quit();
}
界面消失的類似方法(比較笨拙,而且效率差):
void LoginDialog::closeEvent(QCloseEvent *)
{
for(int i=0; i< 100000; i++)
{
if(i<10000)
{
this->setWindowOpacity(0.9);
}
else if(i<20000)
{
this->setWindowOpacity(0.8);
}
else if(i<30000)
{
this->setWindowOpacity(0.7);
}
else if(i<40000)
{
this->setWindowOpacity(0.6);
}
else if(i<50000)
{
this->setWindowOpacity(0.5);
}
else if(i<60000)
{
this->setWindowOpacity(0.4);
}
else if(i<70000)
{
this->setWindowOpacity(0.3);
}
else if(i<80000)
{
this->setWindowOpacity(0.2);
}
else if(i<90000)
{
this->setWindowOpacity(0.1);
}
else
{
this->setWindowOpacity(0.0);
}
}
//進行視窗退出
QApplication::quit();
}
28、Qt擷取系統檔案圖示
1、擷取檔案夾圖示
QFileIconProvider icon_provider;
QIcon icon = icon_provider.icon(QFileIconProvider::Folder);
2、擷取指定檔案圖示
QFileInfo file_info(name);
QFileIconProvider icon_provider;
QIcon icon = icon_provider.icon(file_info);
29、Qt把整形資料轉換成固定長度字元串
有時需要把money的數字轉換成固定格式,如660066轉換成660,066,就需要把整形資料轉換成固定長度字元串(即前面位數補0的效果)。有如下方法:
QString int2String(int num, int size)
{
QString str = QString::number(num);
str = str.rightJustified(size,'0');
return str;
}
或
QString int2String(int number, int size)
{
return QString("%1").arg(number, size, 10, QChar('0'));
}
或
QString int2String(int number, int size)
{
QString str;
str.fill('0', size);
str.push_back(QString::number(number));
str = str.right(size);
return str;
}
故處理數字:
QString value = "";
QString temp = "";
int number = 100060010;
if (number < 1000) {
value = QString::number(number);
}
else if (number < 1000 * 1000) {
value = QString::number(number/1000);
value += ",";
//temp = QString::number(number%1000);
//temp = temp.rightJustified(3,'0');
//temp.fill('0', 3);
//temp.push_back(QString::number(number));
//temp = temp.right(3);
value += QString("%1").arg(number%1000, 3, 10, QChar('0'));
}
else if (number < 1000*1000*1000) {
value = QString::number(number/(1000*1000));
value += ",";
number = number%(1000*1000);
value += QString("%1").arg(number/1000, 3, 10, QChar('0'));
value += ",";
value += QString("%1").arg(number%1000, 3, 10, QChar('0'));
}
qDebug() << "==============" << value;
輸出:============== "100,060,010"
30、QLabel的強大功能
(1)QLabel的自動換行pLabel->setWordWrap(true);
QTextCodec *codec = QTextCodec::codecForName("utf8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
QLabel *pLabel = new QLabel(this);
pLabel->setStyleSheet("color: red");
//pLabel->setAlignment(Qt::AlignCenter);
pLabel->setGeometry(30, 30, 150, 150);
pLabel->setWordWrap(true);
QString strText = QString("床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。");
QString strHeightText = "<p style=\"line-height:%1%\">%2<p>";
strText = strHeightText.arg(150).arg(strText);
pLabel->setText(strText);
(2)QLabel的過長省略加tips,通過QFontMetrics來實作
QTextCodec *codec = QTextCodec::codecForName("utf8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
QLabel *pLabel = new QLabel(this);
pLabel->setStyleSheet("color: red");
pLabel->setGeometry(30, 30, 150, 150);
pLabel->setWordWrap(true);
QString strText = QString("床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。");
QString strElidedText = pLabel->fontMetrics().elidedText(strText, Qt::ElideRight, 150, Qt::TextShowMnemonic);
pLabel->setText(strElidedText);
pLabel->setToolTip(strText);
(3)QLabel的富文本
QTextCodec *codec = QTextCodec::codecForName("utf8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
QLabel *pLabel = new QLabel(this);
pLabel->setStyleSheet("color: red");
//pLabel->setAlignment(Qt::AlignCenter);
pLabel->setGeometry(30, 30, 150, 150);
pLabel->setWordWrap(true);
QString strHTML = QString("<html> \
<head> \
<style> font{color:red;} #f{font-size:18px; color: green;} </style> \
</head> \
<body>\
<font>%1</font><font id=\"f\">%2</font> \
</body> \
</html>").arg("Hello").arg("World");
pLabel->setText(strHTML);
pLabel->setAlignment(Qt::AlignCenter);