Qt淺談之總結(整理)


Qt淺談之總結(整理)

 

來源 http://blog.csdn.net/taiyang1987912/article/details/32713781

一、簡介

       QT的一些知識點總結,方便以后查閱。

二、詳解

1、獲取屏幕的工作區的大小

 
  1. {  
  2.     //獲取屏幕分辨率  
  3.     qDebug()<< "screen width:"<<QApplication::desktop()->width();  
  4.     qDebug()<< "screen height:"<<QApplication::desktop()->height();  
  5.     //下面方法也可以  
  6.     qDebug()<< "screen width:"<<qApp->desktop()->width();  
  7.     qDebug()<< "screen height:"<<qApp->desktop()->height();  
  8.   
  9.     //獲取客戶使用區大小  
  10.     qDebug()<< "screen avaliabe width:"<<QApplication::desktop()->availableGeometry().width();  
  11.     qDebug()<< "screen avaliabe heigth:"<<QApplication::desktop()->availableGeometry().height();  
  12.   
  13.     //獲取應用程序矩形大小  
  14.     qDebug()<< "application avaliabe width:"<<QApplication::desktop()->screenGeometry().width();  
  15.     qDebug()<< "application avaliabe heigth:"<<QApplication::desktop()->screenGeometry().height();  
  16. }  

移動到窗口中央:

move((QApplication::desktop()->width() - width())/2,  (QApplication::desktop()->height() - height())/2);

全屏設置:

setWindowState(Qt::WindowFullScreen);

2、設置應用程序圖標

  1. {      
  2.     QIcon icon;  
  3.     icon.addPixmap(QPixmap(QString::fromUtf8(":/images/logo.png")), QIcon::Normal, QIcon::Off);  
  4.     win->setWindowIcon(icon);  
  5.     win->setIconSize(QSize(256, 256));  
  6. }  

3、顯示圖片Label

  1. {  
  2.     QLabel *logoLabel;  
  3.     logoLabel = new QLabel();  
  4.     logoLabel->setObjectName(QString::fromUtf8("logolabel"));  
  5.     logoLabel->setGeometry(QRect(160, 110, 128, 128));  
  6.     logoLabel->setPixmap(QPixmap(QString::fromUtf8(":/images/logo.png")));  
  7.     logoLabel->setScaledContents(true);  
  8. }  

4、字體更改

  1. {      
  2.     QFont font;  
  3.     font.setPointSize(40);  
  4.     font.setBold(true);  
  5.     font.setWeight(75);  
  6.     QLabel *fontLabel = new QLabel();  
  7.     fontLabel->setFont(font);  
  8. }  

5、文本顏色更改

  1. void Widget::changeColor(QWidget *window, QColor color)  
  2. {  
  3.     QPalette *palette = new QPalette();  
  4.     palette->setColor(QPalette::Text, color);  
  5.     window->setPalette(*palette);  
  6.     delete palette;  
  7. }  

6、時間日期轉QString

  1. QString date_str = QDate::currentDate().toString(QString("yyyyMMdd")); //"yyyyMMdd"為轉換格式,該格式轉換后日期如"20121205"  
  2. QString time_str = QTime::currentTime().toString(QString("hhmmss")); //"hhmmss"為轉換格式,該格式轉換后時間如"080359"  

7、Qt界面風格

  1. 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進入顯示

  1. {  
  2.     slider = new QSlider;  
  3.     slider->setRange(0,100);  
  4.     slider->setTickInterval(10);  
  5.     slider->setOrientation(Qt::Horizontal);  
  6.     slider->setValue(100);  
  7.     slider->setVisible(false);  
  8.     connect(slider,SIGNAL(valueChanged(int)),this,SLOT(slotChanged(int)));  
  9. }  
  10. void PicTrans::enterEvent ( QEvent * )  
  11. {  
  12.     slider->setVisible(true);  
  13. }  
  14.   
  15. void PicTrans::leaveEvent(QEvent *)  
  16. {  
  17.     slider->setVisible(false);  
  18. }  

進入slider顯示,離開slider隱藏。

10、Qt不重復隨機數

  1. {   //qt  
  2.     QTime time; time= QTime::currentTime();   
  3.     qsrand(time.msec()+time.second()*1000);   
  4.     qDebug() << qrand() % 100; //在0-100中產生出隨機數  
  5. }  
 
  1. {   //c語言  
  2.     srand(unsigned(time(0)));  
  3.     int number = rand() % 100; /*產生100以內的隨機整數*/  
  4. }  

11、QSettings保存窗口狀態

  1. void   
  2. Settings::readSettings()  
  3. {  
  4.     QSettings setting("MyPro","settings");  
  5.     setting.beginGroup("Dialog");  
  6.     QPoint pos = setting.value("position").toPoint();  
  7.     QSize size = setting.value("size").toSize();      
  8.     setting.endGroup();  
  9.       
  10.     setting.beginGroup("Content");  
  11.     QColor color = setting.value("color").value<QColor>();  
  12.     QString text = setting.value("text").toString();  
  13.     setting.endGroup();  
  14.       
  15.     move(pos);  
  16.     resize(size);  
  17.     QPalette p = label->palette();  
  18.     p.setColor(QPalette::Normal,QPalette::WindowText,color);  
  19.     label->setPalette(p);  
  20.     edit->setPlainText(text);  
  21. }  
  22.   
  23. void  
  24. Settings::writeSettings()  
  25. {  
  26.     QSettings setting("MyPro","settings");  
  27.     setting.beginGroup("Dialog");  
  28.     setting.setValue("position",pos());  
  29.     setting.setValue("size",size());  
  30.     setting.endGroup();  
  31.       
  32.     setting.beginGroup("Content");  
  33.     setting.setValue("color",label->palette().color(QPalette::WindowText));  
  34.     setting.setValue("text",edit->toPlainText());  
  35.     setting.endGroup();  
  36. }  

12、兩個信號連接同一個槽

參考上述的例8。

  1. connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(slotClick()));  
  2. connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(slotClick()));  

  1. void Dialog::slotClick()  
  2. {  
  3.     QPushButton* btn = dynamic_cast<QPushButton*>(sender());  
  4.     if (btn == ui->btn_ok) {  
  5.         qDebug() << "button:" <<ui->btn_ok->text();  
  6.     }  
  7.     else if (btn == ui->btn_cancel) {  
  8.         qDebug() << "button:" <<ui->btn_cancel->text();  
  9.     }  
  10. }  

有時button類型不同時,可以分別判斷對象指針。

  1. void Dialog::slotClick()  
  2. {  
  3.     ;  
  4.     if ((QPushButton* btn = dynamic_cast<QPushButton*>(sender())) == ui->btn_ok) {  
  5.         qDebug() << "button:" <<ui->btn_ok->text();  
  6.     }  
  7.     else if ((QRadioButton* btn = dynamic_cast<QRadioButton*>(sender())) == ui->btn_cancel) {  
  8.         qDebug() << "button:" <<ui->btn_cancel->text();  
  9.     }  
  10. }  

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控件多選后刪除

  1. setSelectionMode(QAbstractItemView::MultiSelection); //不按ctrl鍵即可多選  
  2. setSelectionMode(QAbstractItemView::ExtendedSelection);  //按ctrl鍵多選  
  3. QModelIndexList indexList = ui->listvFiles->selectionModel()->selectedRows();  
  4. QModelIndex index;  
  5. int i = 0;  
  6. foreach(index, indexList)  
  7. {  
  8.     this->modFileLists.removeRow(index.row() - i);  
  9.     ++i;  
  10. }  

16、QByteArray存入中文時亂碼

  1. QByteArray bytes;  
  2. bytes.append(this->modFileLists.data(this->modFileLists.index(i), Qt::DisplayRole).toString()); //亂碼  
  3.   
  4. QByteArray bytes;  
  5. bytes.append(this->modFileLists.data(this->modFileLists.index(i), Qt::DisplayRole).toString().toLocal8Bit()); //正常  

17、Qt托盤

  1. //使用QSystemTrayIcon類  
  2. QSystemTrayIcon *tray;      //托盤  
  3. QMenu *meuTray;             //托盤菜單  
  4. QAction *acTrayQuit;        //托盤退出  
  5.   
  6. this->tray = new QSystemTrayIcon(this);  
  7. this->meuTray = new QMenu(this);  
  8. this->acTrayQuit = this->meuTray->addAction(QIcon(":/res/image/quit.png"), tr("Quit"));  
  9. connect(this->acTrayQuit, SIGNAL(triggered()), this, SLOT(OnExit()));  
  10.   
  11. this->tray->setContextMenu(this->meuTray);  
  12. this->tray->setIcon(QIcon(":/res/image/tray.ico"));  
  13. this->tray->show();  
  14.   
  15. connect(this->tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(OnTrayActivated(QSystemTrayIcon::ActivationReason)));  
  16.   
  17.   
  18. voidUpdateTerminal::OnTrayActivated(QSystemTrayIcon::ActivationReasonreason)  
  19. {  
  20.     switch(reason)  
  21.     {  
  22.     caseQSystemTrayIcon::DoubleClick:  
  23.         if(this->isHidden())  
  24.             this->show();  
  25.         break;  
  26.     }  
  27. }  

18、Qt遞歸遍歷文件和文件夾

  1. //遞歸遍歷文件夾,找到所有的文件  
  2. //_filePath:要遍歷的文件夾的文件名  
  3. int FindFile(const QString& _filePath)  
  4. {  
  5.     QDir dir(_filePath);  
  6.     if (!dir.exists()) {  
  7.         return -1;  
  8.     }  
  9.   
  10.   //取到所有的文件和文件名,但是去掉.和..的文件夾(這是QT默認有的)  
  11.     dir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);  
  12.   
  13.     //文件夾優先  
  14.     dir.setSorting(QDir::DirsFirst);  
  15.   
  16.     //轉化成一個list  
  17.     QFileInfoList list = dir.entryInfoList();  
  18.     if(list.size()< 1 ) {  
  19.         return -1;  
  20.     }  
  21.     int i=0;  
  22.   
  23.     //遞歸算法的核心部分  
  24.     do{  
  25.         QFileInfo fileInfo = list.at(i);  
  26.         //如果是文件夾,遞歸  
  27.         bool bisDir = fileInfo.isDir();  
  28.         if(bisDir) {  
  29.             FindFile(fileInfo.filePath());  
  30.         }  
  31.         else{  
  32.             //bool isDll = fileInfo.fileName().endsWith(".dll");  
  33.             qDebug() << fileInfo.filePath() << ":" <<fileInfo.fileName();  
  34.         }//end else  
  35.         i++;  
  36.     } while(i < list.size());  
  37. }  

若只想獲取文件名,也可以這樣使用:

  1. int FindFile(const QString& _filePath)  
  2. {  
  3.     QDir dir(_filePath);  
  4.     if (!dir.exists()) {  
  5.         return -1;  
  6.     }  
  7.   
  8.   //取到所有的文件和文件名,但是去掉.和..的文件夾(這是QT默認有的)  
  9.     dir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);  
  10.   
  11.     //文件夾優先  
  12.     dir.setSorting(QDir::DirsFirst);  
  13.   
  14.     //轉化成一個list  
  15.     QFileInfoList list = dir.entryInfoList();  
  16.     QStringList infolist = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);  
  17.     if(list.size()< 1 ) {  
  18.         return -1;  
  19.     }  
  20.     int i=0;  
  21.   
  22.     //遞歸算法的核心部分  
  23.     do{  
  24.         QFileInfo fileInfo = list.at(i);  
  25.         //如果是文件夾,遞歸  
  26.         bool bisDir = fileInfo.isDir();  
  27.         if(bisDir) {  
  28.             FindFile(fileInfo.filePath());  
  29.         }  
  30.         else{  
  31.             for(int m = 0; m <infolist.size(); m++) {  
  32.                                 //這里是獲取當前要處理的文件名  
  33.                 qDebug() << infolist.at(m);  
  34.             }  
  35.             break;  
  36.         }//end else  
  37.         i++;  
  38.     } while(i < list.size());  
  39. }  

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
  1. QStringList  list;  
  2. list<< "-t" << "--s" << "3600";  
  3. QProcess::startDetached("Shutdown.exe",list);   
  4. // QProcess::execute("Shutdown.exe",list);  

(2)創建QProcess,使用start函數

 可以查看外部程序返回的數據,輸出結果。

  1. QProcess *pProces = new QProcess(this);  
  2. connect(pProces, SIGNAL(readyRead()),this, SLOT(on_read()));  
  3. QStringList list;  
  4. pProces->start("Shutdown.exe", list);  
  5.   
  6. void on_read()  
  7. {  
  8.   QProcess *pProces = (QProcess *)sender();  
  9.   QString result = pProces->readAll();  
  10.   QMessageBox::warning(NULL, "", result);  
  11. }  

(3)執行的是程序,如route、ipconfig

  1. QProcess p(0);  
  2. p.start("route");  
  3. p.waitForStarted();  
  4. p.waitForFinished();  
  5. qDebug()<<QString::fromLocal8Bit(p.readAllStandardError());  
  1. QProcess p(0);  
  2. p.start("ipconfig");  
  3. p.waitForStarted();  
  4. p.waitForFinished();  
  5. qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());  

(4)執行的是命令,如dir

  1. QProcess p(0);  
  2. p.start("cmd");  
  3. p.waitForStarted();  
  4. p.write("dir\n");  
  5. p.closeWriteChannel();  
  6. p.waitForFinished();  
  7. qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());  

或者:

  1. QProcess p(0);  
  2. p.start("cmd", QStringList()<<"/c"<<"dir");  
  3. p.waitForStarted();  
  4. p.waitForFinished();  
  5. qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());  

(5)QProcess使用管道(命令中不支持管道符|)
一個進程的標准輸出流到目標進程的標准輸入:command1 | command2。

  1. QProcess process1;  
  2. QProcess process2;  
  3. process1.setStandardOutputProcess(&process2);  
  4. process1.start("command1");  
  5. process2.start("command2");  

 

20、當前系統Qt所支持的字體

 
  1. QFontDatabase database;  
  2.    foreach (QString strFamily, database.families()) {  
  3.       qDebug() <<"family:" << strFamily;  
  4.       foreach (QString strStyle, database.styles(strFamily)) {  
  5.          qDebug() << "-----style:" << strStyle;  
  6.       }  
  7.    }  

系統中所有支持中文的字體名稱

  1. QFontDatabase database;    
  2. foreach (const QString &family, database.families(QFontDatabase::SimplifiedChinese))     
  3. {    
  4.     qDebug()<<family;    
  5. }    

中文亂碼:

  1. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));  
  2. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));  

21、IP正則匹配

  1. {      
  2.     /**********judge ip**********/  
  3.     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]?)");  
  4.     if(!regExp.exactMatch(ip)) {  
  5.         flag  = false;  
  6.         ipAddressLineEdit->clear();  
  7.         ipAddressLineEdit->setError(true);  
  8.         ipAddressLineEdit->setHint(tr("           IpAddress is wrong"));  
  9.     }  
  10.     else  flag = true;  
  11.   
  12. }  

22、QPushButton去掉虛線框

  1. QPushButton:focus{padding: -1;}  
  2. /* 
  3. {border-style:flat;}    //扁平 
  4. button->setFlat(true) 
  5. ui->checkBox->setFocusPolicy(Qt::NoFocus); 
  6. ui->radioButton->setFocusPolicy(Qt::NoFocus);   
  7. */  

23、Qt臨時獲得root權限

(1)getuid()函數返回一個調用程序的真實用戶ID,使用root執行程序時getuid()返回值為0。

  1. if (getuid() != 0)  
  2. {  
  3.     QMessageBox::information(0, QString(QObject::tr("Warnning")),  
  4.                              QString(QObject::tr("do not use root privage")),  
  5.                              QString(QObject::tr("OK")));  
  6.     return -1;  
  7. }  

(2)臨時獲得root權限

使用getuid()/setuid()函數,讓程序臨時獲得root權限代碼。

  1. /*   
  2.  * gcc -g -o test-uid test-uid.c  
  3.  * chown root.root ./test-uid  
  4.  * chmod 4755 ./test-uid  
  5.  * ls -al /var  
  6.  * */  
  7. #include<stdio.h>    
  8. #include<unistd.h>    
  9. #include<sys/types.h>    
  10. int main(int argc, char **argv)    
  11. {    
  12.   // save user uid    
  13.   uid_t uid = getuid();    
  14.   // get root authorities    
  15.   if(setuid(0)) {    
  16.         printf("test-uid: setuid error");    
  17.         return -1;    
  18.   }    
  19.   printf("test-uid: run as root, setuid is 0\n");    
  20.   system ("touch /var/testroot");    
  21.     
  22.   // rollback user authorities    
  23.   if(setuid(uid)) {    
  24.         printf("test-uid: setuid error");    
  25.         return -1;    
  26.   }    
  27.   printf("test-uid: run as user, setuid is %d\n", uid);    
  28.   system ("touch /var/testuser");    
  29.     
  30.   return 0;    
  31. }  

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編。
選一下任意試試:
  1. QTextCodec::setCodecForTr(QTextCodec::codecForLocale());  
  2. QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));  
  3. QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF8"));  
//獲取系統編碼,否則移植會出現亂碼
QTextCodec*codec = QTextCodec::codecForName("System");
//設置和對本地文件系統讀寫時候的默認編碼格式
QTextCodec::setCodecForLocale(codec);
//設置傳給tr函數時的默認字符串編碼
QTextCodec::setCodecForTr(codec);
//用在字符常量或者QByteArray構造QString對象時使用的一種編碼方式
QTextCodec::setCodecForCStrings(codec); 
支持linux單一系統時:
  1. QTextCodec *codec = QTextCodec::codecForName("utf8");  
  2. QTextCodec::setCodecForLocale(codec);  
  3. QTextCodec::setCodecForCStrings(codec);  
  4. QTextCodec::setCodecForTr(codec);  

26、圖片做背景縮放

  1. QPixmap backGroundPix = QPixmap(":/resources/images/login.png");  
  2. QMatrix martix;  
  3. martix.scale(0.95, 0.9);  
  4. backGroundPix = backGroundPix.transformed(martix);  
  5. resize(backGroundPix.width(),  backGroundPix.height());  
  6. QPalette palette;  
  7. palette.setBrush(QPalette::Window,QBrush(backGroundPix));  
  8. setPalette(palette);  

或者:

  1. QPixmap backGroundPix;  
  2. backGroundPix.load(":/resources/images/login.png");  
  3. setAutoFillBackground(true);   // 這個屬性一定要設置  
  4. QPalette pal(palette());  
  5. pal.setBrush(QPalette::Window, QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio, \  
  6.                                      Qt::SmoothTransformation)));  
  7. 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的效果)。有如下方法:

  1. QString int2String(int num, int size)  
  2. {  
  3.    QString str = QString::number(num);  
  4.    str = str.rightJustified(size,'0');  
  5.    return str;  
  6. }  

  1. QString int2String(int number, int size)  
  2. {  
  3.     return QString("%1").arg(number, size, 10, QChar('0'));  
  4. }  

  1. QString int2String(int number, int size)  
  2. {  
  3.     QString str;  
  4.     str.fill('0', size);  
  5.     str.push_back(QString::number(number));  
  6.     str = str.right(size);  
  7.     return str;  
  8. }  

故處理數字:

  1. QString value = "";  
  2. QString temp = "";  
  3. int number = 100060010;  
  4. if (number 1000) {  
  5.     value = QString::number(number);  
  6. }  
  7. else if (number 1000 * 1000) {  
  8.     value = QString::number(number/1000);  
  9.     value += ",";  
  10.     //temp = QString::number(number%1000);  
  11.     //temp = temp.rightJustified(3,'0');  
  12.     //temp.fill('0', 3);  
  13.     //temp.push_back(QString::number(number));  
  14.     //temp = temp.right(3);  
  15.     value += QString("%1").arg(number%1000, 3, 10, QChar('0'));  
  16. }  
  17. else if (number 1000*1000*1000) {  
  18.     value = QString::number(number/(1000*1000));  
  19.     value += ",";  
  20.     number = number%(1000*1000);  
  21.     value += QString("%1").arg(number/1000, 3, 10, QChar('0'));  
  22.     value += ",";  
  23.     value += QString("%1").arg(number%1000, 3, 10, QChar('0'));  
  24.   
  25. }  
  26. qDebug() << "==============" <value;  

輸出:============== "100,060,010"

30、QLabel的強大功能

(1)QLabel的自動換行pLabel->setWordWrap(true);

  1. QTextCodec *codec = QTextCodec::codecForName("utf8");  
  2. QTextCodec::setCodecForLocale(codec);  
  3. QTextCodec::setCodecForCStrings(codec);  
  4. QTextCodec::setCodecForTr(codec);  
  5. QLabel *pLabel = new QLabel(this);  
  6. pLabel->setStyleSheet("color: red");  
  7. //pLabel->setAlignment(Qt::AlignCenter);  
  8. pLabel->setGeometry(30, 30, 150, 150);  
  9. pLabel->setWordWrap(true);  
  10. QString strText = QString("床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。");  
  11. QString strHeightText = "<p style=\"line-height:%1%\">%2<p>";  
  12. strText = strHeightText.arg(150).arg(strText);  
  13. pLabel->setText(strText);  

 

(2)QLabel的過長省略加tips,通過QFontMetrics來實現

  1. QTextCodec *codec = QTextCodec::codecForName("utf8");  
  2. QTextCodec::setCodecForLocale(codec);  
  3. QTextCodec::setCodecForCStrings(codec);  
  4. QTextCodec::setCodecForTr(codec);  
  5. QLabel *pLabel = new QLabel(this);  
  6. pLabel->setStyleSheet("color: red");  
  7. pLabel->setGeometry(30, 30, 150, 150);  
  8. pLabel->setWordWrap(true);  
  9. QString strText = QString("床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。");  
  10. QString strElidedText = pLabel->fontMetrics().elidedText(strText, Qt::ElideRight, 150, Qt::TextShowMnemonic);  
  11. pLabel->setText(strElidedText);  
  12. pLabel->setToolTip(strText);  

(3)QLabel的富文本

  1. QTextCodec *codec = QTextCodec::codecForName("utf8");  
  2. QTextCodec::setCodecForLocale(codec);  
  3. QTextCodec::setCodecForCStrings(codec);  
  4. QTextCodec::setCodecForTr(codec);  
  5. QLabel *pLabel = new QLabel(this);  
  6. pLabel->setStyleSheet("color: red");  
  7. //pLabel->setAlignment(Qt::AlignCenter);  
  8. pLabel->setGeometry(30, 30, 150, 150);  
  9. pLabel->setWordWrap(true);  
  10. QString strHTML = QString("<html> \  
  11.                              <head> \  
  12.                                 <style> font{color:red;} #f{font-size:18px; color: green;} </style> \  
  13.                              </head> \  
  14.                              <body>\  
  15.                                <font>%1</font><font id=\"f\">%2</font> \  
  16.                               </body> \  
  17.                            </html>").arg("Hello").arg("World");  
  18. pLabel->setText(strHTML);  
  19. pLabel->setAlignment(Qt::AlignCenter);  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM