• Qt浅谈之总结(整理)


    Qt浅谈之总结(整理)

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

    一、简介

           QT的一些知识点总结,方便以后查阅。

    二、详解

    1、获取屏幕的工作区的大小

     
    1. {  
    2.     //获取屏幕分辨率  
    3.     qDebug()<< "screen "<<QApplication::desktop()->width();  
    4.     qDebug()<< "screen height:"<<QApplication::desktop()->height();  
    5.     //下面方法也可以  
    6.     qDebug()<< "screen "<<qApp->desktop()->width();  
    7.     qDebug()<< "screen height:"<<qApp->desktop()->height();  
    8.   
    9.     //获取客户使用区大小  
    10.     qDebug()<< "screen avaliabe "<<QApplication::desktop()->availableGeometry().width();  
    11.     qDebug()<< "screen avaliabe heigth:"<<QApplication::desktop()->availableGeometry().height();  
    12.   
    13.     //获取应用程序矩形大小  
    14.     qDebug()<< "application avaliabe "<<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 ");  
    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 ");    
    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 ", 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);  

  • 相关阅读:
    美化盒子和文本字体
    图片和多媒体
    学习node1_module对象
    学习vue5_组件
    学习vue4_input
    学习vue3
    学习vue2
    Ubuntu中U盘识别不了
    docker 建立新用户软件安装环境ubuntu
    计算机性能优化笔记
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/7811275.html
Copyright © 2020-2023  润新知