Qt淺談之總結(整理)
來源 http://blog.csdn.net/taiyang1987912/article/details/32713781
一、簡介
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
- 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窗口的透明度設置
在構造函數里添加代碼,需要添加頭文件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);