Qt总结(整理)

来源:互联网 发布:js json特殊字符处理 编辑:程序博客网 时间:2024/06/05 18:00

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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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、设置应用程序图标

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片

在Windows平台为应用程序设置图标:

第一步:创建一个包含图标图像的ICO文件,并将其保存在源文件目录下,可命名为myapp.ico;

第二步:创建一个.rc文件,包含如下内容:

IDI_ICON1               ICON    DISCARDABLE     "myappico.ico" 
第三步:

如果你是使用qmake生成makefile文件,那么你只需要在工程文件myapp.pro文件中写入如下内容:

RC_FILE = myapp.rc 
再次编译程序,即可达到效果



3、显示图片Label

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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、字体更改

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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、文本颜色更改

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. QString date_str = QDate::currentDate().toString(QString("yyyyMMdd")); //"yyyyMMdd"为转换格式,该格式转换后日期如"20121205"  
  2. QString time_str = QTime::currentTime().toString(QString("hhmmss")); //"hhmmss"为转换格式,该格式转换后时间如"080359"  

7、Qt界面风格

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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进入显示

[cpp] view plaincopy
  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不重复随机数

[cpp] view plaincopy
  1. {   //qt  
  2.     QTime time; time= QTime::currentTime();   
  3.     qsrand(time.msec()+time.second()*1000);   
  4.     qDebug() << qrand() % 100; //在0-100中产生出随机数  
  5. }  
[cpp] view plaincopy
  1. {   //c语言  
  2.     srand(unsigned(time(0)));  
  3.     int number = rand() % 100; /*产生100以内的随机整数*/  
  4. }  

11、QSettings保存窗口状态

[cpp] view plaincopy
  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。
[cpp] view plaincopy
  1. connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(slotClick()));  
  2. connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(slotClick()));  
[cpp] view plaincopy
  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类型不同时,可以分别判断对象指针。

[cpp] view plaincopy
  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语言家->更新翻译
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);
  }//否则默认用英文

14、item-view控件多选后删除

[cpp] view plaincopy
  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. }  

15、QByteArray存入中文时乱码

[cpp] view plaincopy
  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()); //正常  

16、Qt托盘

[cpp] view plaincopy
  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. }  

17、Qt递归遍历文件和文件夹

[cpp] view plaincopy
  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. }  
若只想获取文件名,也可以这样使用:
[cpp] view plaincopy
  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. }  

18、Qt调用外部程序

(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
[html] view plaincopy
  1. QStringList  list;  
  2. list<< "-t" << "--s" << "3600";  
  3. QProcess::startDetached("Shutdown.exe",list);   
  4. // QProcess::execute("Shutdown.exe",list);  
(2)创建QProcess,使用start函数

        可以查看外部程序返回的数据,输出结果。

[html] view plaincopy
  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
[html] view plaincopy
  1. QProcess p(0);  
  2. p.start("route");  
  3. p.waitForStarted();  
  4. p.waitForFinished();  
  5. qDebug()<<QString::fromLocal8Bit(p.readAllStandardError());  
[html] view plaincopy
  1. QProcess p(0);  
  2. p.start("ipconfig");  
  3. p.waitForStarted();  
  4. p.waitForFinished();  
  5. qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());  

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

[html] view plaincopy
  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());  
或者:

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

18、当前系统Qt所支持的字体

系统支持的所有字体的名称

[cpp] view plaincopy
  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.    }  
系统中所有支持中文的字体名称
[cpp] view plaincopy
  1. QFontDatabase database;    
  2. foreach (const QString &family, database.families(QFontDatabase::SimplifiedChinese))     
  3. {    
  4.     qDebug()<<family;    
  5. }    

中文乱码:

[html] view plaincopy
  1. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));  
  2. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));  

19、IP正则匹配

[cpp] view plaincopy
  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. }  

20、QPushButton去掉虚线框

[cpp] view plaincopy
  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. */  

21、Qt临时获得root权限


(1)getuid()函数返回一个调用程序的真实用户ID,使用root执行程序时getuid()返回值为0。

[cpp] view plaincopy
  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权限代码。

[cpp] view plaincopy
  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;    

0 0
原创粉丝点击