Qt實用小技巧(轉)

原博網址:http://www.cnblogs.com/feiyangqingyun/archive/2010/12/06/1898143.htmlphp

 

1、若是在窗體關閉前自行判斷是否可關閉
答:從新實現這個窗體的 closeEvent()函數,加入判斷操做html


void MainWindow::closeEvent(QCloseEvent *event)
{
   if (maybeSave())
   {
writeSettings();
event->accept();
   }
   else
   {
event->ignore();
   }
}


2、如何用打開和保存文件對話框
答:使用QFileDialogmysql

 

QString fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty())
{
   loadFile(fileName);
}linux


   QString fileName = QFileDialog::getSaveFileName(this);
   if (fileName.isEmpty())
   {
return false;
   }

 

 

若是用qt自帶的話:程序員

選擇文件夾sql

QFileDialog* openFilePath = new QFileDialog( this, " 請選擇文件夾", "file");     //打開一個目錄選擇對話框
openFilePath-> setFileMode( QFileDialog:irectoryOnly );
if ( openFilePath->exec() == QDialog::Accepted )
{
   //code here!
}
delete openFilePath;數據庫

 

選擇文件:編程

QFileDialog *openFilePath = new QFileDialog(this);
openFilePath->setWindowTitle(tr("請選擇文件"));
openFilePath->setDirectory(".");
openFilePath->setFilter(tr("txt or image(*.jpg *.png *.bmp *.tiff *.jpeg *.txt)"));
if(openFilePath->exec() == QDialog::Accepted) 
{
     //code here
}
delete openFilePath;windows


7、如何使用警 告、信息等對話框
答:使用QMessageBox類的靜態方法app


int ret = QMessageBox::warning(this, tr("Application"),
   tr("The document has been modified.\n"
"Do you want to save your changes?"),
   QMessageBox::Yes | QMessageBox:efault,
   QMessageBox::No,
   QMessageBox::Cancel | QMessageBox::Escape);
if (ret == QMessageBox::Yes)
return save();
else if (ret == QMessageBox::Cancel)
return false;

或者簡單點兒:

QMessageBox::information(this, "關於","盲人輔助系統(管理端)!\nVersion:1.0\nNo Copyright");



9、在Windows下Qt裏爲何沒有終端輸出?
答:把下面的配置項加入到.pro文件中


win32:CONFIG += console

十一、想在源代碼中直接使用中文,而不使用tr()函數進行轉換,怎麼辦?
答:在main函數中加入下面三條語句,但並不提倡

QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));

或者

QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));


使用GBK仍是使用UTF-8,依源文件中漢字使用的內碼而定
這樣,就可在源文件中直接使用中文,好比:

QMessageBox::information(NULL, "信息", "關於本軟件的演示信息", QMessageBox::Ok, QMessageBox::NoButtons);


十二、爲何將開發的使用數據庫的程序發佈到其它機器就鏈接不上數據庫?
答:這是因爲程序找不到數據庫插件而致,可照以下解決方 法:
在main函數中加入下面語句:

QApplication::addLibraryPath(strPluginsPath");


strPluginsPath是插件所在目錄,好比此目錄爲/myapplication/plugins
則將須要的sql驅 動,好比qsqlmysql.dll, qsqlodbc.dll或對應的.so文件放到
/myapplication/plugins/sqldrivers/
目 錄下面就好了
這是一種解決方法,還有一種通用的解決方法,即在可執行文件目錄下寫qt.conf文件,把系統相關的一些目錄配置寫到 qt.conf文件裏,詳細狀況情參考Qt Document Reference裏的qt.conf部分


1三、如何建立QT使 用的DLL(.so)以及如何使用此DLL(.so)
答:建立DLL時其工程使用lib模板

TEMPLATE=lib


而源文件則和使用普通的源文件同樣,注意把頭文件和源文件分開,由於在其它程序使用此DLL時須要此頭文件
在使用此DLL時,則 在此工程源文件中引入DLL頭文件,並在.pro文件中加入下面配置項:

LIBS += -Lyourdlllibpath -lyourdlllibname

Windows下和Linux下一樣(Windows下生成的DLL文件名爲yourdlllibname.dll而在Linux下生成 的爲libyourdlllibname.so。注意,關於DLL程序的寫法,聽從各平臺級編譯器所定的規則。

1四、如何啓動一個外部程 序
答:一、使用QProcess::startDetached()方法,啓動外部程序後當即返回;
二、使用 QProcess::execute(),不過使用此方法時程序會最阻塞直到此方法執行的程序結束後返回,這時候可以使用QProcess和QThread 這兩個類結合使用的方法來處理,以防止在主線程中調用而致使阻塞的狀況
先從QThread繼承一個類,從新實現run()函數:

class MyThread : public QThread
{
public:
   void run();
};

void MyThread::run()
{
QProcess::execute("notepad.exe");
}


這樣,在使用的時候則可定義一個MyThread類型的成員變量,使用時調用其start()方法:


class ...............
{...........
MyThread thread;
............
};

.....................
thread.start();

 


1九、如何製做不規則形狀的窗體或部件
答:請參考下面的帖子
http://www.qtcn.org/bbs/read.php?tid=8681

20、刪除數據庫時出現"QSqlDatabasePrivate::removeDatabase: connection 'xxxx' is still in use, all queries will cease to work"該如何處理
答:出現此種錯誤 是由於使用了鏈接名字爲xxxx的變量做用域沒有結束,解決方法是在全部使用了xxxx鏈接的數據庫組件變量的做用域都結束後再使用 QSqlDatabase::removeDatabae("xxxx")來刪除鏈接。

2一、如何顯示一個圖片並使其隨窗體同步縮放
答: 下面給出一個從QWidget派生的類ImageWidget,來設置其背景爲一個圖片,並可隨着窗體改變而改變,其實從下面的代碼中能夠引伸出其它許多 方法,若是須要的話,能夠從這個類再派生出其它類來使用。
頭文件: ImageWidget.hpp

#ifndef IMAGEWIDGET_HPP
#define IMAGEWIDGET_HPP

#include <QtCore>
#include <QtGui>

class ImageWidget : public QWidget
{
Q_OBJECT
public:
ImageWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~ImageWidget();
protected:
void resizeEvent(QResizeEvent *event);
private:
QImage _image;
};

#endif


CPP文件: ImageWidget.cpp

#include "ImageWidget.hpp"

ImageWidget::ImageWidget(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
_image.load("image/image_background");
setAutoFillBackground(true);   // 這個屬性必定要設置
QPalette pal(palette());
pal.setBrush(QPalette::Window, 
QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio, 
Qt::SmoothTransformation)));
setPalette(pal);
}

ImageWidget::~ImageWidget()
{
}

// 隨着窗體變化而設置背景
void ImageWidget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
QPalette pal(palette());
pal.setBrush(QPalette::Window, 
QBrush(_image.scaled(event->size(), Qt::IgnoreAspectRatio, 
Qt::SmoothTransformation)));
setPalette(pal);
}


2二、Windows下如何讀串口信息
答:可經過註冊表來讀qt4.1.0 讀取註冊表獲得 串口信息的方法!

 

 

 

 

23.背景修改

QString filename = "E:\圖片\壁紙\1.jpg";
QPixmap pixmap(filename);
pal.setBrush(QPalette::Window,QBrush(pixmap));
setPalette(pal);   

 

24.載入某個指定類型文件

openFileName = QFileDialog::getOpenFileName(this,tr("Open Image"), "/home/picture", tr("Image Files (*.png *.tif *.jpg *.bmp)"));    
if (!openFileName.isEmpty())
{
   Ui_Project_UiClass::statusBar->showMessage("當前打開的文件:" + openFileName); 
   label_2->setPixmap(QPixmap(openFileName)); 
}

25.QText亂碼問題
發佈到別的機器上後,中文全是亂碼。gb18030和 gb2312我都試過了,都是亂碼。 
main.cpp裏設置以下:
QTextCodec *codec = QTextCodec::codecForName("System"); 
QTextCodec::setCodecForLocale(codec); 
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec); 
把 gb2312改爲System就能夠了
#include <QTextCodec>


26.圖片問題
用label就能夠載入圖片,方法:
label->setPixmap(QPixmap(「path(可 以用geifilename函數獲得)」));
可是這樣的label沒有滾動條,很不靈活,能夠這樣處理:
在QtDesign中建立一個 QScrollArea控件,設置一些屬性,而後在代碼中新建一個label指針,在cpp的構造函數中用new QLabel(this)初始化(必定要有this,否則後面setWidget會出錯)。而後再:
scrollArea->setWidget(label_2);
scrollArea->show();

27.佈局
最後要充滿窗口,點擊最外層的窗口空白處。再點擊水平layout便可

28.程序圖標   
準備一個ICO圖標,把這個圖標複製到程序的主目錄下,姑且名字 叫」myicon.ico」吧。而後編寫一個icon.rc文件。裏面只有一行文字:
IDI_ICON1               ICON                    「myicon.ico」
最後,在工程的pro文件里加入一行:
RC_FILE = icon.rc
qmake和make一下,就能夠發現你的應用程序擁有漂亮的圖標了。

29.回車輸出
QT中操做文件,從文件流QTextStream輸出回車到txt的方法 是<< 'r' << endl;

30.QListView的添加或者刪除

QStringList user;
user += "first";
user +="second";
QStringListModel *model = new QStringListModel(user);
userList->setModel(model);        //useList是個QListView
user += "third";
model->setStringList(user);

31.設置背景音樂

若是隻是簡單的設置背景音樂的話。用QSound。具體查看qt助手。

windows下的QSound 只能播放wav格式哦。。

32.禁止QAbstractItemView的子類的雙擊修改功能。

好比listview,雙擊某個item就會成爲編輯模式。禁止此功能。用:

QAbstractItemVIew`s name->setEditTriggers(QAbstractItemView::NoEditTriggers);

33.qt對文件的操做

讀文件    
QFile inputFile(":/forms/input.txt");
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString line = in.readAll();
inputFile.close();

寫文件    
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) 
{
    fprintf(stderr, "Could not open %s for writing: %s\n",
            qPrintable(filename),
            qPrintable(file.errorString()));
    return false;
}
file.write(data->readAll());
file.close();

將某個路徑轉化爲當前系統承認的路徑
QDir::convertSeparators(openFileName)

獲取當前路徑
QDir currentPath;                       
QString filePath = currentPath.absolutePath (); 
QString path = QDir::convertSeparators(filePath + "/" +clickedClass);

一些操做
QFile::exists(fileName)
QFile::Remove();

文件打開模式
if(file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::ReadOnly)

 

34.qt確認對話框

QMessageBox   mb(tr("刪除確認"), tr("確認刪除此項?"),
   QMessageBox:uestion,
   QMessageBox::Yes   |   QMessageBox:efault,
   QMessageBox::No     |   QMessageBox::Escape,
   QMessageBox::NoButton);   
if(mb.exec() == QMessageBox::No)   
   return;

35.QListView
QStringList user;
user += "first";
user +="second";
QStringListModel *model = new QStringListModel(user);
QListView user_id->setModel(model);
user += "third"; //下面2步是更新
model->setStringList(user);

 

36.容許這樣的語句:Layout->setGeometry( QRect( 10,10,100,50 ) ); QHBoxLayout等佈局對象(but not widget )裏的 Widget 的排列,是按其加入的前後順序而定的。要讓其顯示在一個窗口上,須要把讓這個窗口做爲其 Parent.

37.setMargin() sets the width of the outer border. This is the width of the reserved space along each of the QBoxLayout's four sides. 就是設置其周圍的空白距離。

38.setSpacing() sets the width between neighboring boxes. (You can use addSpacing() to get more space at a particular spot. ) 就是設置相鄰對象間的距離。

39.addStretch() to create an empty, stretchable box. 至關於加入了一個空白的不顯示的部件。

40.Qt程序的全屏幕顯示:
//全屏幕顯示
//main_window->setGeometry( 0, 0, QApplication::desktop()->width(), QApplication::desktop()->height() );
//或者:
main_window->resize( QApplication::desktop()->width(), QApplication::desktop()->height() );

實際上只有第一種方法能夠。第二種方法只是把窗口大小調整爲屏幕大小,可是因爲其顯示位置未定,因此顯示出來仍是不行。第一種方法直接設置了窗口的顯示位置爲屏幕左上角。
Qapplication::desktop() 返回了一個 QdesktopWidget 的對象指針。
全屏幕顯示後,windows下依然沒法擋住任務欄。(爲了實現跨平臺性,最好仍是用 Qt提供的方法。例如這裏用的就是 Qt的方法,而不是用的Windows API)

41.使用如下代碼能夠爲一個窗口部件加入背景圖 片:
QPixmap pic;
pic.load( "qqpet.bmp" );
Label.setPixmap( pic );
Label.show();

QpushButton 也能夠。可是在使用了 setPixmap 後,原來的文字就顯示不了了。若是在setPixmap後設置文字,則圖片就顯示不了。
其餘事項:the constructor of QPixmap() acept char * only for xpm image.
hope file is placed proper and is bmp. jpg's gif's can cause error(configure).----不能縮放圖象。

42. 調用 void QWidget::setFocus () [virtual slot] 便可設置一個焦點到一個物體上。

43.讓窗 口保持固定大小:
main_window->setMinimumSize( g_main_window_w, g_main_window_h );
main_window->setMaximumSize( g_main_window_w, g_main_window_h );
只要讓最小尺寸和最大尺寸相等便可。

44.得到系統日期:
QDate Date = QDate::currentDate();
int year = Date.year();
int month = Date.month();
int day = Date.day();

45.得到系統時間:
QTime Time = QTime::currentTime();
int hour = Time.hour();
int minute = Time.minute();
int second = Time.second();

46.QString::number 能夠直接傳其一個數而返回一個 QString 對象。
所以能夠用如下代碼:
m_textedit->setText( QString::number( 10 ) );

47.利用 QString::toInt() 之類的接口能夠轉換 字符串爲數。這就能夠把 QLineEdit之類返回的內容轉換格式。
文檔裏的描述:
int QString::toInt ( bool * ok = 0, int base = 10 ) const 
Returns the string converted to an int value to the base base, which is 10 by default and must be between 2 and 36. 
If ok is not 0: if a conversion error occurs, *ok is set to FALSE; otherwise *ok is set to TRUE.

48.關於 QTimer .
文 檔:
QTimer is very easy to use: create a QTimer, call start() to start it and connect its timeout() to the appropriate slots. When the time is up it will emit the timeout() signal. 
Note that a QTimer object is destroyed automatically when its parent object is destroyed.
能夠這樣作:
QTimer *time = new QTimer( this );
Timer->start( 1000, false ); //每1000ms timer-out一次,並一直工做(false ),爲 true只工做一次。
Connect( timer, SIGNAL( timeout() ), this, SLOT( dealTimer() ) );

49.關於QSpinBox:
QSpinBox allows the user to choose a value either by clicking the up/down buttons to increase/decrease the value currently displayed or by typing the value directly into the spin box. If the value is entered directly into the spin box, Enter (or Return) must be pressed to apply the new value. The value is usually an integer.
以下方式建立:
QSpinBox *spin_box = new QSpinBox( 0, 100, 1, main_window );
spin_box->setGeometry( 10,10, 20, 10 );

這樣建立後,它只容許輸入數字,能夠設置其幾何大小。
使用int QSpinBox::value () const獲得其當前值。

50.Main 能夠這樣:
clock->show();
int result = a.exec();
delete clock;
return result;

51. Qt 中的中文:
若是使程序只支持一種編碼,也能夠直接把整個應用程序的編碼設置爲GBK編碼, 而後在字符串以前 加tr(QObject::tr), 
#include <qtextcodec.h>

qApp->setDefaultCodec( QTextCodec::codecForName("GBK") ); 
QLabel *label = new QLabel( tr("中文標籤") );

52. Qt顯示中文最簡單辦法

QString str;
str = QString::fromLocal8Bit(".....");
QLabel tLabel(str, 0);

53. 去除標題欄和邊框
Widget(parent,
Qt::WDestructiveClose | Qt::WStyle_Customize | Qt::WStyle_NoBorder)


54.修改程序主窗口標題
setWindowTitle(QString &); //Qt 4

55. 給Qt應用程序加圖標

1,準備ico圖標, 好比myappico.ico

2, 建個rc文本文件名, 好比myrc.rc
在裏面加入IDI_ICON1 ICON DISCARDABLE "myappico.ico"

3, 在pro工程文件中加入
setWindowIcon(QIcon("myappico.ico")); //通常應該加到class::public QWdiget中.由於
setWindowIcon()是QWidget public function
56. 如何在Qt程序中加入OpenGL支持。 在QT程序中加入OpenGL支持很簡 單,只須要在Kdevelop鏈接的庫中加入「-lGL -lGLU」便可,若是須要glut支持,還能夠加入「-lglut」。具體操做是在kdevelop集成編譯環境中按下」F7」,在彈出的對話框中選擇 「Linker」一項,在輸入欄輸入你想添加的庫便可,寫法與gcc/g++一致。 通常在類QGLWidget中使用OpenGL,調用此類的 頭文件是qgl.h,具體寫法請參考qt例程中的gear,texture,box等程序(在RedHat7.2中,它們在/usr/lib/qt- 2.3.1/doc/examples下). 57. 檢驗linux/Unix環境是否支持OpenGL. Qt中的 QGLFormat類能夠幫助咱們輕易檢驗系統是否支持OpenGL,載入頭文件(#include <qgl.h>)後,咱們就可使用QGLFormat的靜態函數hasOpenGL來檢驗,具體寫法以下例: if (!QGLFormat::hasOpenGL()) //Test OpenGL Environment { qWarning( "This system has no OpenGL support. Exiting." );//彈出警告對話框 return -1; } 58. 得到屏幕的高和寬. 通常咱們能夠經過QT的Qapplication類來得到系統的一些信息,載入頭文件(#include <qapplication.h>)咱們就能夠調用它,下例是使主程序充滿整個屏幕的代碼: Gui_MainForm gui_mainform; a.setMainWidget( &gui_mainform ); gui_mainform.resize( QApplication::desktop()->width(), QApplication::desktop()->height() ); gui_mainform.show(); 59.關 於信號和槽. 信號和槽機制是QT庫的重要特性,能夠說不了解它就不瞭解Qt.此機制能在各種間創建方便快捷的通訊聯繫,只要類中加載了 Q_OBJECT宏並用 connect函數正確鏈接在一塊兒便可,具體寫法這裏就不贅述了.但本人在使用過程當中發現使用此機制容易破壞程序的結構性和封裝性,速度也不是很讓人滿 意,尤爲是在跨多類調用時.鄙人的一孔之見是: 信號和槽機制不可不用,但不可多用. 60.QT程序中界面的設計. 儘管 Kdevelop是一個優秀的集成編譯環境,可遺憾的是它不是一個可視化的編譯環境,好在有Qdesigner來幫助咱們完成界面設計,該程序的使用 很簡單,使用過VB,VC和Delphi的程序員能很快其操做方式,操做完成後存盤會生成一個擴展名爲」ui」的文件,你接下來的任務就是把它解析成 cpp和h文件,假設文件名爲myform.ui,解析方法以下: $uic myform.ui –I myform.h –o myform..cpp //這句生成cpp文件 $uic myform.ui –o myform.h //這句生成h文件. 61. 由pro文件生成Makefile. 對於Linux/Unix程序員來講編寫Makefile文件是一項使人煩惱的任務,而qt程序員就沒有這樣 的煩惱,一句$qmake –o Makefile myprogram.pro就能夠輕鬆愉快的完成任務,而pro文件的編寫也很容易,其核心是h和cpp文件的簡單列表.具體寫法請參考一下qt自帶的樣 例和教程吧(在RedHat7.2中,它在/usr/lib/qt-2.3.1/doc/examples下),相對Makefile文件簡直沒有什麼難 度. 62.主組件的選擇. 通常咱們在編程是使用繼承Qwidget類的類做爲主組件,這固然未可厚非.但在製做典型的多文檔和 單文檔程序時咱們有更好的選擇— QmainWindow類,它能夠方便的管理其中的菜單工具條主窗口和狀態條等,在窗體幾何屬性發生變化時也能完美的實現內部組件縮放,這比用傳統的幾何 佈局類來管理要方便得多,並且不用寫什麼代碼.關於它的具體細節請查閱QT的幫組文檔,這裏就不贅述了. 63.菜單項中加入 Checked項. 在QT中,菜單項中加入Checked有點麻煩,具體寫法以下: 1> 定義int型成員變量,並在建立菜單項中寫: displayGeometryMode=new QPopupMenu(this); //這裏建立彈出菜單組displayGeometryMode m_menuIDWire=displayGeometryMode-> insertItem("Wire",this,SLOT(slt_Change2WireMode()));.//建立彈出菜單子項 displayGeometryMode->setItemChecked(m_ menuIDWire,true);//設定此子項爲選擇狀態 2> 再在槽函數中寫: displayGeometryMode->setItemChecked(m_menuIDWire,false);// 這裏設定此子項爲非選擇狀態 64.截獲程序即將退出的信號. 有些時候咱們須要在程序即將退出時進行一些處理,如保存文件等等.如 何截獲程序退出的信號呢?仍是要用到Qapplication類的aboutToQuit()信號,程序中能夠這樣寫: connect(qApp,SIGNAL(aboutToQuit()),this,SLOT(Slot_SaveActions())); 在 槽函數Slot_SaveActions()就能夠進行相關處理了,注意,使用全局對象qApp須要加載頭文件(#include <qapplication.h>). 65.彈出標準文件對話框. 在程序中彈出文件對話框是很容易處理的,舉例如 下: QString filter="Txt files(*.txt)\n" //設置文件過濾,缺省顯示文本文件 "All files(*)" ; //可選擇顯示全部文件 QString Filepathname=QFileDialog::getOpenFileName(" ",filter,this);//彈出對話框,這句須要加載頭文件(#include < qfiledialog.h >) 66. 將當前日期時間轉化爲標準Qstring. QDateTime currentdatetime =QDateTime::currentDateTime();//須要加載頭文件(#include < qdatetime.h >) QString strDateTime=currentdatetime.toString(); 67.設置定時器 全部Qobject的子類 在設置定時器時都沒必要加載一個Qtimer對象,由於這樣形成了資源浪費且須要書寫多餘的函數,很不方便.最好的辦法是重載timerEvent函數,具 體寫法以下: class Gui_DlgViewCtrlDatum : public QDialog { Q_OBJECT public: Gui_DlgViewCtrlDatum( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 ); ~Gui_DlgViewCtrlDatum(); protected: void timerEvent( QTimerEvent * ); }; void Gui_DlgViewCtrlDatum::timerEvent( QTimerEvent *e ) { //statements } 再在Gui_DlgViewCtrlDatum的構造函 數中設置時間間隔: startTimer(50);//單位爲毫秒 這樣,每隔50毫秒,函數timerEvent便會被調用一 次. 68.最方便的幾何佈局類QGridLayout 在QT的幾何佈局類中,筆者認爲QgridLayout使用最爲方便,舉例 以下: QGridLayout* layout=new QGridLayout(this,10,10);//建立一個10*10的QgridLayout實例 layout->addMultiCellWidget(gui_dlgslab_glwnd,1,8,0,7);// 將OpenGL窗口固定在QgridLayout中的(1,0)單元格到(8,7)單元格中 layout->addMultiCellWidget(Slider1,0,9,8,8);// 將一個slider固定在單元格(0,8)到(9,8)中 layout->addWidget(UpLimitLbl,1,9);//將一 個label(UpLimitLbl)固定在單元格(1,9)中 這樣,不管窗體大小如何改變,它們的佈局方式都不會發生改變,這比反覆使用 QvboxLayout和QhboxLayout要方便快捷許多. 注:使用幾何佈局類須要調用頭文件(#include <qlayout.h>) 69.字符串類Qstring和字符串鏈表類QstringList. Qstring是 Qt中標準字符串類,下面列出它的一些經常使用函數: toInt():將字符串轉化成int類型. ToFloat():將字符串轉化成 float類型. ToDouble():將字符串轉化成double類型. Left(n):從左起取n個字符 Right(n): 從右起取n個字符 SetNum(n):將實數n(包括int,float,double等)轉化爲Qsting型. QstringList 是你們比較少使用的類,它能夠當作Qstring組成的鏈表(QT中標準鏈表類Qlist的函數對它都適用,它的單個節點是Qstring類型的),特別 適合與處理文本,下面一段代碼就可見其方便快捷: Qstring strtmp=」abc|b|c|d」; QstringList strlsttmp; Strlsttmp =QStringList::split("|", strtmp); For(unsigned int I=0;I< Strlsttmp.count();I++) { cout<< Strlsttmp.at(I); } 結果輸出爲:abc b c d,也就是說,經過一個函數split,一行文本就被符號」|」自動分割成了單個字符串.這在文本處理時特別省力.(請參考c語言大全第四版中 用」strtok」函數分割文本的例程,將雙方比較一下) 70. QGLWidget類如何加入鼠標支持. QGLWidget類 加入鼠標支持須要重載如下函數: void mousePressEvent(QMouseEvent*); void mouseMoveEvent(QMouseEvent*); void mouseReleaseEvent(QMouseEvent*); 請 具體看一個實例: class Gui_WgtMain_GLWnd : public QGLWidget { Q_OBJECT public: Gui_WgtMain_GLWnd(QWidget *parent=0, const char *name=0); ~Gui_WgtMain_GLWnd(); protected: void initializeGL(); void paintGL(); void resizeGL( int w, int h ); void mousePressEvent(QMouseEvent*); void mouseMoveEvent(QMouseEvent*); void mouseReleaseEvent(QMouseEvent*); private: int m_nCnt; }; void Gui_WgtMain_GLWnd::mousePressEvent(QMouseEvent* e) { //statements } void Gui_WgtMain_GLWnd:: mouseMoveEvent (QMouseEvent* e) { //statements } void Gui_WgtMain_GLWnd:: mouseReleaseEvent (QMouseEvent* e) { //statements } 其 中, e->x();e->y();能夠得到鼠標的位置, e->button()能夠取得鼠標按鍵的狀態(左中右鍵以及ctrl,alt,shift等組合鍵),靈活使用他們就能夠在用鼠標操做 OpenGL畫面了. 71.由ui文件生成.h和.cpp文件 生成.cpp文件 $uic myform.ui -i myform.h -o myform.cpp 生成.h文件 $uic myform.ui -o myform.h
相關文章
相關標籤/搜索