日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > c/c++ >内容正文

c/c++

QT小技巧

發(fā)布時(shí)間:2025/4/5 c/c++ 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 QT小技巧 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、如果在窗體關(guān)閉前自行判斷是否可關(guān)閉
答:重新實(shí)現(xiàn)這個(gè)窗體的 closeEvent()函數(shù),加入判斷操作


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


2、如何用打開(kāi)和保存文件對(duì)話框
答:使用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, " 請(qǐng)選擇文件夾", "file");???? //打開(kāi)一個(gè)目錄選擇對(duì)話框
openFilePath-> setFileMode( QFileDialog:irectoryOnly );
if ( openFilePath->exec() == QDialog::Accepted )
{
?? //code here!
}
delete openFilePath;

?

選擇文件:

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


7、如何使用警 告、信息等對(duì)話框
答:使用QMessageBox類的靜態(tài)方法


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;

或者簡(jiǎn)單點(diǎn)兒:

QMessageBox::information(this, "關(guān)于","盲人輔助系統(tǒng)(管理端)!\nVersion:1.0\nNo Copyright");



9、在Windows下Qt里為什么沒(méi)有終端輸出?
答:把下面的配置項(xiàng)加入到.pro文件中


win32:CONFIG += console

11、想在源代碼中直接使用中文,而不使用tr()函數(shù)進(jìn)行轉(zhuǎn)換,怎么辦?
答:在main函數(shù)中加入下面三條語(yǔ)句,但并不提倡

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,依源文件中漢字使用的內(nèi)碼而定
這樣,就可在源文件中直接使用中文,比如:

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


12、為什么將開(kāi)發(fā)的使用數(shù)據(jù)庫(kù)的程序發(fā)布到其它機(jī)器就連接不上數(shù)據(jù)庫(kù)?
答:這是由于程序找不到數(shù)據(jù)庫(kù)插件而致,可照如下解決方 法:
在main函數(shù)中加入下面語(yǔ)句:

QApplication::addLibraryPath(strPluginsPath");


strPluginsPath是插件所在目錄,比如此目錄為/myapplication/plugins
則將需要的sql驅(qū) 動(dòng),比如qsqlmysql.dll, qsqlodbc.dll或?qū)?yīng)的.so文件放到
/myapplication/plugins/sqldrivers/
目 錄下面就行了
這是一種解決方法,還有一種通用的解決方法,即在可執(zhí)行文件目錄下寫(xiě)qt.conf文件,把系統(tǒng)相關(guān)的一些目錄配置寫(xiě)到 qt.conf文件里,詳細(xì)情況情參考Qt Document Reference里的qt.conf部分


13、如何創(chuàng)建QT使 用的DLL(.so)以及如何使用此DLL(.so)
答:創(chuàng)建DLL時(shí)其工程使用lib模板

TEMPLATE=lib


而源文件則和使用普通的源文件一樣,注意把頭文件和源文件分開(kāi),因?yàn)樵谄渌绦蚴褂么薉LL時(shí)需要此頭文件
在使用此DLL時(shí),則 在此工程源文件中引入DLL頭文件,并在.pro文件中加入下面配置項(xiàng):

LIBS += -Lyourdlllibpath -lyourdlllibname

Windows下和Linux下同樣(Windows下生成的DLL文件名為yourdlllibname.dll而在Linux下生成 的為libyourdlllibname.so。注意,關(guān)于DLL程序的寫(xiě)法,遵從各平臺(tái)級(jí)編譯器所定的規(guī)則。

14、如何啟動(dòng)一個(gè)外部程 序
答:1、使用QProcess::startDetached()方法,啟動(dòng)外部程序后立即返回;
2、使用 QProcess::execute(),不過(guò)使用此方法時(shí)程序會(huì)最阻塞直到此方法執(zhí)行的程序結(jié)束后返回,這時(shí)候可使用QProcess和QThread 這兩個(gè)類結(jié)合使用的方法來(lái)處理,以防止在主線程中調(diào)用而導(dǎo)致阻塞的情況
先從QThread繼承一個(gè)類,重新實(shí)現(xiàn)run()函數(shù):

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

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


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


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

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

?


19、如何制作不規(guī)則形狀的窗體或部件
答:請(qǐng)參考下面的帖子
http://www.qtcn.org/bbs/read.php?tid=8681

20、刪除數(shù)據(jù)庫(kù)時(shí)出現(xiàn)"QSqlDatabasePrivate::removeDatabase: connection 'xxxx' is still in use, all queries will cease to work"該如何處理
答:出現(xiàn)此種錯(cuò)誤 是因?yàn)槭褂昧诉B接名字為xxxx的變量作用域沒(méi)有結(jié)束,解決方法是在所有使用了xxxx連接的數(shù)據(jù)庫(kù)組件變量的作用域都結(jié)束后再使用 QSqlDatabase::removeDatabae("xxxx")來(lái)刪除連接。

21、如何顯示一個(gè)圖片并使其隨窗體同步縮放
答: 下面給出一個(gè)從QWidget派生的類ImageWidget,來(lái)設(shè)置其背景為一個(gè)圖片,并可隨著窗體改變而改變,其實(shí)從下面的代碼中可以引申出其它許多 方法,如果需要的話,可以從這個(gè)類再派生出其它類來(lái)使用。
頭文件: 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);?? // 這個(gè)屬性一定要設(shè)置
QPalette pal(palette());
pal.setBrush(QPalette::Window,?
QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio,?
Qt::SmoothTransformation)));
setPalette(pal);
}

ImageWidget::~ImageWidget()
{
}

// 隨著窗體變化而設(shè)置背景
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下如何讀串口信息
答:可通過(guò)注冊(cè)表來(lái)讀
qt4.1.0 讀取注冊(cè)表得到 串口信息的方法!

?

?

?


23.背景修改

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

?

24.載入某個(gè)指定類型文件

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

25.QText亂碼問(wèn)題
發(fā)布到別的機(jī)器上后,中文全是亂碼。gb18030和 gb2312我都試過(guò)了,都是亂碼。?
main.cpp里設(shè)置如下:
QTextCodec *codec = QTextCodec::codecForName("System");?
QTextCodec::setCodecForLocale(codec);?
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);?
把 gb2312改成System就可以了
#include <QTextCodec>


26.圖片問(wèn)題
用label就可以載入圖片,方法:
label->setPixmap(QPixmap(“path(可 以用geifilename函數(shù)得到)”));
但是這樣的label沒(méi)有滾動(dòng)條,很不靈活,可以這樣處理:
在QtDesign中創(chuàng)建一個(gè) QScrollArea控件,設(shè)置一些屬性,然后在代碼中新建一個(gè)label指針,在cpp的構(gòu)造函數(shù)中用new QLabel(this)初始化(一定要有this,不然后面setWidget會(huì)出錯(cuò))。然后再:
scrollArea->setWidget(label_2);
scrollArea->show();

27.布局
最后要充滿窗口,點(diǎn)擊最外層的窗口空白處。再點(diǎn)擊水平layout即可

28.程序圖標(biāo)???
準(zhǔn)備一個(gè)ICO圖標(biāo),把這個(gè)圖標(biāo)復(fù)制到程序的主目錄下,姑且名字 叫”myicon.ico”吧。然后編寫(xiě)一個(gè)icon.rc文件。里面只有一行文字:
IDI_ICON1?????????????? ICON??????????????????? “myicon.ico”
最后,在工程的pro文件里加入一行:
RC_FILE = icon.rc
qmake和make一下,就可以發(fā)現(xiàn)你的應(yīng)用程序擁有漂亮的圖標(biāo)了。

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

30.QListView的添加或者刪除

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

31.設(shè)置背景音樂(lè)

如果只是簡(jiǎn)單的設(shè)置背景音樂(lè)的話。用QSound。具體查看qt助手。

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

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

比如listview,雙擊某個(gè)item就會(huì)成為編輯模式。禁止此功能。用:

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

33.qt對(duì)文件的操作

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

寫(xiě)文件????
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();

將某個(gè)路徑轉(zhuǎn)化為當(dāng)前系統(tǒng)認(rèn)可的路徑
QDir::convertSeparators(openFileName)

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

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

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

?

34.qt確認(rèn)對(duì)話框

QMessageBox?? mb(tr("刪除確認(rèn)"), tr("確認(rèn)刪除此項(xiàng)?"),
?? 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.允許這樣的語(yǔ)句:Layout->setGeometry( QRect( 10,10,100,50 ) ); QHBoxLayout等布局對(duì)象(but not widget )里的 Widget 的排列,是按其加入的先后順序而定的。要讓其顯示在一個(gè)窗口上,需要把讓這個(gè)窗口作為其 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. 就是設(shè)置其周圍的空白距離。

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

39.addStretch() to create an empty, stretchable box. 相當(dāng)于加入了一個(gè)空白的不顯示的
部件。

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

實(shí)際上只有第一種方法可以。第二種方法只是把窗口大小
調(diào)整為屏幕大小,但是由于其顯示位置未定,所以顯示出來(lái)還是不行。第一種方法直接設(shè)置了窗口的顯示位置為屏幕左上角。
Qapplication::desktop() 返回了一個(gè) QdesktopWidget 的對(duì)象指針。
全屏幕顯示后,windows下依然無(wú)法擋住任務(wù)欄。(為了實(shí)現(xiàn)跨平臺(tái)性,最好還是用 Qt提供的方法。例如這里用的就是 Qt的方法,而不是用的Windows API)

41.使用以下代碼可以為一個(gè)窗口部件加入背景圖 片:
QPixmap pic;
pic.load( "qqpet.bmp" );
Label.setPixmap( pic );
Label.show();

QpushButton 也可以。但是在使用了 setPixmap 后,原來(lái)的文字就顯示不了了。如果在setPixmap后設(shè)置文字,則圖片就顯示不了。
其他事項(xiàng):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. 調(diào)用 void QWidget::setFocus () [virtual slot] 即可設(shè)置一個(gè)焦點(diǎn)到一個(gè)物體上。

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

44.獲得系統(tǒng)日期:
QDate Date = QDate::currentDate();
int year = Date.year();
int month = Date.month();
int day = Date.day();

45.獲得系統(tǒng)時(shí)間:
QTime Time = QTime::currentTime();
int hour = Time.hour();
int minute = Time.minute();
int second = Time.second();

46.QString::number 可以直接傳其一個(gè)數(shù)而返回一個(gè) QString 對(duì)象。
因此可以用以下代碼:
m_textedit->setText( QString::number( 10 ) );

47.利用 QString::toInt() 之類的接口可以轉(zhuǎn)換 字符串為數(shù)。這就可以把 QLineEdit之類返回的內(nèi)容轉(zhuǎn)換格式。
文檔里的描述:
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.關(guān)于 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.關(guān)于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.
如下方式創(chuàng)建:
QSpinBox *spin_box = new QSpinBox( 0, 100, 1, main_window );
spin_box->setGeometry( 10,10, 20, 10 );

這樣創(chuàng)建后,它只允許輸入數(shù)字,可以設(shè)置其幾何大小。
使用int QSpinBox::value () const得到其當(dāng)前值。

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

51. Qt 中的中文:
如果使程序只支持一種編碼,也可以直接把整個(gè)應(yīng)用程序的編碼設(shè)置為GBK編碼, 然后在字符串之前 加tr(QObject::tr),?
#include <qtextcodec.h>

qApp->setDefaultCodec( QTextCodec::codecForName("GBK") );?
QLabel *label = new QLabel( tr("中文標(biāo)簽") );

52. Qt顯示中文最簡(jiǎn)單辦法

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

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


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

55. 給Qt應(yīng)用程序加圖標(biāo)

1,準(zhǔn)備ico圖標(biāo), 比如myappico.ico

2, 建個(gè)rc文本文件名, 比如myrc.rc
在里面加入IDI_ICON1 ICON DISCARDABLE "myappico.ico"

3, 在pro工程文件中加入
setWindowIcon(QIcon("myappico.ico")); //一般應(yīng)該加到class::public QWdiget中.因?yàn)?br />setWindowIcon()是QWidget public function
56. 如何在Qt程序中加入OpenGL支持。
在QT程序中加入OpenGL支持很簡(jiǎn) 單,只需要在Kdevelop連接的庫(kù)中加入“-lGL -lGLU”即可,如果需要glut支持,還可以加入“-lglut”。具體操作是在kdevelop集成編譯環(huán)境中按下”F7”,在彈出的對(duì)話框中選擇 “Linker”一項(xiàng),在輸入欄輸入你想添加的庫(kù)即可,寫(xiě)法與gcc/g++一致。
一般在類QGLWidget中使用OpenGL,調(diào)用此類的 頭文件是qgl.h,具體寫(xiě)法請(qǐng)參考qt例程中的gear,texture,box等程序(在RedHat7.2中,它們?cè)?usr/lib/qt- 2.3.1/doc/examples下).

57. 檢驗(yàn)linux/Unix環(huán)境是否支持OpenGL.
Qt中的 QGLFormat類可以幫助我們輕易檢驗(yàn)系統(tǒng)是否支持OpenGL,載入頭文件(#include <qgl.h>)后,我們就可以使用QGLFormat的靜態(tài)函數(shù)hasOpenGL來(lái)檢驗(yàn),具體寫(xiě)法如下例:
if (!QGLFormat::hasOpenGL()) //Test OpenGL Environment
{
qWarning( "This system has no OpenGL support. Exiting." );//彈出警告對(duì)話框
return -1;
}

58. 獲得屏幕的高和寬.
一般我們可以通過(guò)QT的Qapplication類來(lái)獲得系統(tǒng)的一些信息,載入頭文件(#include <qapplication.h>)我們就可以調(diào)用它,下例是使主程序充滿整個(gè)屏幕的代碼:
Gui_MainForm gui_mainform;
a.setMainWidget( &gui_mainform );
gui_mainform.resize( QApplication::desktop()->width(), QApplication::desktop()->height() ); gui_mainform.show();

59.關(guān) 于信號(hào)和槽.
信號(hào)和槽機(jī)制是QT庫(kù)的重要特性,可以說(shuō)不了解它就不了解Qt.此機(jī)制能在各類間建立方便快捷的通信聯(lián)系,只要類中加載了 Q_OBJECT宏并用 connect函數(shù)正確連接在一起即可,具體寫(xiě)法這里就不贅述了.但本人在使用過(guò)程中發(fā)現(xiàn)使用此機(jī)制容易破壞程序的結(jié)構(gòu)性和封裝性,速度也不是很讓人滿 意,尤其是在跨多類調(diào)用時(shí).鄙人的一孔之見(jiàn)是: 信號(hào)和槽機(jī)制不可不用,但不可多用.

60.QT程序中界面的設(shè)計(jì).
盡管 Kdevelop是一個(gè)優(yōu)秀的集成編譯環(huán)境,可遺憾的是它不是一個(gè)可視化的編譯環(huán)境,好在有Qdesigner來(lái)幫助我們完成界面設(shè)計(jì),該程序的使用 很簡(jiǎn)單,使用過(guò)VB,VC和Delphi的程序員能很快其操作方式,操作完成后存盤會(huì)生成一個(gè)擴(kuò)展名為”ui”的文件,你接下來(lái)的任務(wù)就是把它解析成 cpp和h文件,假設(shè)文件名為myform.ui,解析方法如下:
$uic myform.ui –I myform.h –o myform..cpp //這句生成cpp文件
$uic myform.ui –o myform.h //這句生成h文件.

61. 由pro文件生成Makefile.
對(duì)于Linux/Unix程序員來(lái)說(shuō)編寫(xiě)Makefile文件是一項(xiàng)令人煩惱的任務(wù),而qt程序員就沒(méi)有這樣 的煩惱,一句$qmake –o Makefile myprogram.pro就可以輕松愉快的完成任務(wù),而pro文件的編寫(xiě)也很容易,其核心是h和cpp文件的簡(jiǎn)單列表.具體寫(xiě)法請(qǐng)參考一下qt自帶的樣 例和教程吧(在RedHat7.2中,它在/usr/lib/qt-2.3.1/doc/examples下),相對(duì)Makefile文件簡(jiǎn)直沒(méi)有什么難 度.

62.主組件的選擇.
一般我們?cè)诰幊淌鞘褂美^承Qwidget類的類作為主組件,這當(dāng)然未可厚非.但在制作典型的多文檔和 單文檔程序時(shí)我們有更好的選擇— QmainWindow類,它可以方便的管理其中的菜單工具條主窗口和狀態(tài)條等,在窗體幾何屬性發(fā)生變化時(shí)也能完美的實(shí)現(xiàn)內(nèi)部組件縮放,這比用傳統(tǒng)的幾何 布局類來(lái)管理要方便得多,而且不用寫(xiě)什么代碼.關(guān)于它的具體細(xì)節(jié)請(qǐng)查閱QT的幫組文檔,這里就不贅述了.

63.菜單項(xiàng)中加入 Checked項(xiàng).
在QT中,菜單項(xiàng)中加入Checked有點(diǎn)麻煩,具體寫(xiě)法如下:
1> 定義int型成員變量,并在創(chuàng)建菜單項(xiàng)中寫(xiě):
displayGeometryMode=new QPopupMenu(this); //這里創(chuàng)建彈出菜單組displayGeometryMode
m_menuIDWire=displayGeometryMode-> insertItem("Wire",this,SLOT(slt_Change2WireMode()));.//創(chuàng)建彈出菜單子項(xiàng)
displayGeometryMode->setItemChecked(m_ menuIDWire,true);//設(shè)定此子項(xiàng)為選擇狀態(tài)

2> 再在槽函數(shù)中寫(xiě):
displayGeometryMode->setItemChecked(m_menuIDWire,false);// 這里設(shè)定此子項(xiàng)為非選擇狀態(tài)

64.截獲程序即將退出的信號(hào).
有些時(shí)候我們需要在程序即將退出時(shí)進(jìn)行一些處理,如保存文件等等.如 何截獲程序退出的信號(hào)呢?還是要用到Qapplication類的aboutToQuit()信號(hào),程序中可以這樣寫(xiě):
connect(qApp,SIGNAL(aboutToQuit()),this,SLOT(Slot_SaveActions()));
在 槽函數(shù)Slot_SaveActions()就可以進(jìn)行相關(guān)處理了,注意,使用全局對(duì)象qApp需要加載頭文件(#include <qapplication.h>).

65.彈出標(biāo)準(zhǔn)文件對(duì)話框.
在程序中彈出文件對(duì)話框是很容易處理的,舉例如 下:
QString filter="Txt files(*.txt)\n" //設(shè)置文件過(guò)濾,缺省顯示文本文件
"All files(*)" ; //可選擇顯示所有文件
QString Filepathname=QFileDialog::getOpenFileName(" ",filter,this);//彈出對(duì)話框,這句需要加載頭文件(#include < qfiledialog.h >)


66. 將當(dāng)前日期時(shí)間轉(zhuǎn)化為標(biāo)準(zhǔn)Qstring.
QDateTime currentdatetime =QDateTime::currentDateTime();//需要加載頭文件(#include < qdatetime.h >)
QString strDateTime=currentdatetime.toString();

67.設(shè)置定時(shí)器
所有Qobject的子類 在設(shè)置定時(shí)器時(shí)都不必加載一個(gè)Qtimer對(duì)象,因?yàn)檫@樣造成了資源浪費(fèi)且需要書(shū)寫(xiě)多余的函數(shù),很不方便.最好的辦法是重載timerEvent函數(shù),具 體寫(xiě)法如下:
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的構(gòu)造函 數(shù)中設(shè)置時(shí)間間隔:
startTimer(50);//單位為毫秒

這樣,每隔50毫秒,函數(shù)timerEvent便會(huì)被調(diào)用一 次.

68.最方便的幾何布局類QGridLayout
在QT的幾何布局類中,筆者認(rèn)為QgridLayout使用最為方便,舉例 如下:
QGridLayout* layout=new QGridLayout(this,10,10);//創(chuàng)建一個(gè)10*10的QgridLayout實(shí)例
layout->addMultiCellWidget(gui_dlgslab_glwnd,1,8,0,7);// 將OpenGL窗口固定在QgridLayout中的(1,0)單元格到(8,7)單元格中
layout->addMultiCellWidget(Slider1,0,9,8,8);// 將一個(gè)slider固定在單元格(0,8)到(9,8)中
layout->addWidget(UpLimitLbl,1,9);//將一 個(gè)label(UpLimitLbl)固定在單元格(1,9)中
這樣,無(wú)論窗體大小如何改變,它們的布局方式都不會(huì)發(fā)生改變,這比反復(fù)使用 QvboxLayout和QhboxLayout要方便快捷許多.
注:使用幾何布局類需要調(diào)用頭文件(#include <qlayout.h>)

69.字符串類Qstring和字符串鏈表類QstringList.
Qstring是 Qt中標(biāo)準(zhǔn)字符串類,下面列出它的一些常用函數(shù):
toInt():將字符串轉(zhuǎn)化成int類型.
ToFloat():將字符串轉(zhuǎn)化成 float類型.
ToDouble():將字符串轉(zhuǎn)化成double類型.
Left(n):從左起取n個(gè)字符
Right(n): 從右起取n個(gè)字符
SetNum(n):將實(shí)數(shù)n(包括int,float,double等)轉(zhuǎn)化為Qsting型.

QstringList 是大家比較少使用的類,它可以看成Qstring組成的鏈表(QT中標(biāo)準(zhǔn)鏈表類Qlist的函數(shù)對(duì)它都適用,它的單個(gè)節(jié)點(diǎn)是Qstring類型的),特別 適合與處理文本,下面一段代碼就可見(jiàn)其方便快捷:
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);
}
結(jié)果輸出為:abc b c d,也就是說(shuō),通過(guò)一個(gè)函數(shù)split,一行文本就被符號(hào)”|”自動(dòng)分割成了單個(gè)字符串.這在文本處理時(shí)特別省力.(請(qǐng)參考c語(yǔ)言大全第四版中 用”strtok”函數(shù)分割文本的例程,將雙方比較一下)

70. QGLWidget類如何加入鼠標(biāo)支持.
QGLWidget類 加入鼠標(biāo)支持需要重載以下函數(shù):
void mousePressEvent(QMouseEvent*);
void mouseMoveEvent(QMouseEvent*);
void mouseReleaseEvent(QMouseEvent*);
請(qǐng) 具體看一個(gè)實(shí)例:
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();可以獲得鼠標(biāo)的位置, e->button()可以取得鼠標(biāo)按鍵的狀態(tài)(左中右鍵以及ctrl,alt,shift等組合鍵),靈活使用他們就可以在用鼠標(biāo)操作 OpenGL畫(huà)面了.

71.由ui文件生成.h和.cpp文件
生成.cpp文件
$uic myform.ui -i myform.h -o myform.cpp

生成.h文件
$uic myform.ui -o myform.h

總結(jié)

以上是生活随笔為你收集整理的QT小技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。