Qt小技巧

1、如果在窗體關閉前自行判斷是否可關閉
答:重新實現這個窗體的 closeEvent()函數,加入判斷操作
void MainWindow::closeEvent(QCloseEvent *event)
{
   if (maybeSave())
   {
writeSettings();
event->accept();
   }
   else
   {
event->ignore();
   }
}
2、如何用打開和保存文件對話框
答:使用QFileDialog

 

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


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

 

 

如果用qt自帶的話:

選擇文件夾

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;


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


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

11、想在源代碼中直接使用中文,而不使用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);


12、爲什麼將開發的使用數據庫的程序發佈到其它機器就連接不上數據庫?
答:這是由於程序找不到數據庫插件而致,可照如下解決方 法:
在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部分


13、如何創建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程序的寫法,遵從各平臺級編譯器所定的規則。

14、如何啓動一個外部程 序
答:1、使用QProcess::startDetached()方法,啓動外部程序後立即返回;
2、使用 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();

 


19、如何製作不規則形狀的窗體或部件
答:請參考下面的帖子
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")來刪除連接。

21、如何顯示一個圖片並使其隨窗體同步縮放
答: 下面給出一個從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);
}


22、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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章