QTimer *timer = new QTimer( this);
2> 得到系統當前時間
QTime time = QTime::currentTime();
3> 窗口 widget 相關
setWindowTitle(tr( "My Title ")); // 設置窗口標題
width();// 窗口寬度
4> 窗口(widget) 事件回調相關 (具體參考 widget.h 文件)
5> QT 畫布(QPainter)的使用
- QColor hourColor(127, 0, 127); // 畫筆顏色
- QPainter painter(objWidget); // 創建一個畫布, objWidget 為當前 畫筆的要畫到哪里, 一般為 Widget 對象
- // 設置畫布的樣式
- painter.setPen(Qt::NoPen);
- painter.setBrush(hourColor);
- painter.translate(width() / 2, height() / 2); // 畫布坐標系統的移動(當前窗口的中心點位置)
- painter.scale(side / 200.0, side / 200.0); // 設置縮放
- painter.rotate(30.0); // 坐標系統,旋轉 30 度
- painter.save();
- painter.drawLine(92, 0, 96, 0);
- // 常用函數(參考QPainter.h)
- void drawText()
- void fillRect()
- void drawPoint()
- void drawPoints(const QPoint *points, int pointCount);
- void drawLine(int x1, int y1, int x2, int y2);
- void drawLines(const QLineF *lines, int lineCount);
- void drawRect(int x1, int y1, int w, int h);
- void drawRects(const QRectF *rects, int rectCount);
- void drawEllipse(int x, int y, int w, int h);
- void drawPolyline(const QPointF *points, int pointCount);
- void drawText(const QPointF &p, const QString &s);
- void drawImage() // 可以繪制圖片
- void eraseRect()
- void scale(qreal sx, qreal sy); // 設置縮放
- void rotate(qreal a);// 設置旋轉
- void setBackground(const QBrush &bg); // 設置背景顏色
- void setPen(const QColor &color); // 設置畫筆
- // 畫一個路徑( QPainterPath 可以存儲 painter 的路徑信息)
- QPainterPath clock; // 初始化一個鍾表的形狀
- clock.addEllipse(-50.0, -50.0, 100.0, 100.0);
- clock.addEllipse(-48.0, -48.0, 96.0, 96.0);
- clock.moveTo(0.0, 0.0);
- clock.lineTo(-2.0, -2.0);
- clock.lineTo(0.0, -42.0);
- clock.lineTo(2.0, -2.0);
- clock.lineTo(0.0, 0.0);
- clock.moveTo(0.0, 0.0);
- clock.lineTo(2.732, -0.732);
- clock.lineTo(24.495, 14.142);
- clock.lineTo(0.732, 2.732);
- clock.lineTo(0.0, 0.0);
- QPainter painter(objWidget); // 創建一個畫布, objWidget 為當前 畫筆的要畫到哪里, 一般為 Widget 對象
- painter.fillPath(clock, Qt::blue);
- // 繪制一個文本
- QPainterPath text;
- QFont font;
- font.setPixelSize(50);
- QRect fontBoundingRect = QFontMetrics(font).boundingRect(tr("Qt"));
- text.addText(-QPointF(fontBoundingRect.center()), font, tr("Qt"));
- QPainter painter(objWidget); // 創建一個畫布, objWidget 為當前 畫筆的要畫到哪里, 一般為 Widget 對象
- painter.fillPath(text, Qt::blue); // 繪制一個文本
- QGridLayout *mainLayout = new QGridLayout;
- // 2行 3列的一個網格布局
- for (int i = 0; i < 2; ++i) { // 行
- for (int j = 0; j < 3; ++j) { // 列
- glWidgets[i][j] = new GLWidget(0, 0);
- mainLayout->addWidget(glWidgets[i][j], i, j); // 直接將其他窗口對象,添加到 mainLayout 中就可以
- }
- }
- setLayout(mainLayout); // 調用窗口對象的 setLayout 方法來設置布局
7> QT 控件的使用 總結
- QComboBox 下拉選擇控件
- shapeComboBox = new QComboBox;
- shapeComboBox->addItem(tr("Clock"));
- shapeComboBox->addItem(tr("House"));
- shapeComboBox->addItem(tr("Text"));
- shapeComboBox->addItem(tr("Truck"));
- // 置回調函數 operationChanged
- connect(shapeComboBox, SIGNAL(activated(int)), this, SLOT(shapeSelected(int)));
- // 回到函數中, index 為當前選擇的索引
- void Window::shapeSelected(int index)
- {
- }
- int index = shapeComboBox->currentIndex(); // 可以得到當前選擇的索引
- // Table View 的使用
- QStandardItemModel model(4, 2); // 設置表格的數據模型 ( 4 行 2 列)
- QTableView tableView; // 表格對象
- tableView.setModel(&model);// 設置數據模型
- // 設置表格對象的數據顯示
- for (int row = 0; row < 10; ++row)
- {
- for (int column = 0; column < 5; ++column)
- {
- QModelIndex index = model.index(row, column, QModelIndex()); // 得到某一個具體的數據索引
- model.setData(index, QVariant("aaaa")); // 設置數據
- }
- }
- model.setColumnCount(5); // 設置表格的列數
- model.setRowCount(2); // 設置表格的行數
- model.insertColumn(1); // 在第 1列后面,插入一列
- model.insertRow(1); // 在第 1 行后面,插入一列
- model.rowCount(); // 表格行數
- model.columnCount(); // 表格列數
菜單相關
- // MainWindow 為主窗口的對象指針
- // Action初始化 -- 一個 Action 相當於 一個具體的菜單項
- actionShow_Test_Dialog = new QAction(MainWindow);
- actionShow_Test_Dialog->setObjectName(QString::fromUtf8("actionShow_Test_Dialog"));
- actionOpen = new QAction(MainWindow);
- actionOpen->setObjectName(QString::fromUtf8("actionOpen"));
- actionSave = new QAction(MainWindow);
- actionSave->setObjectName(QString::fromUtf8("actionSave"));
- actionShow_Table = new QAction(MainWindow);
- actionShow_Table->setObjectName(QString::fromUtf8("actionShow_Table"));
- // QMenuBar 菜單欄, 上面可以放很多的 QMenu
- menuBar = new QMenuBar(MainWindow);
- menuBar->setObjectName(QString::fromUtf8("menuBar"));
- menuBar->setGeometry(QRect(0, 0, 400, 22));
- // QMenu 菜單, 一個菜單上,可以放很多的 Action
- menuFile = new QMenu(menuBar);
- menuFile->setObjectName(QString::fromUtf8("menuFile"));
- menuTest = new QMenu(menuBar);
- menuTest->setObjectName(QString::fromUtf8("menuTest"));
- MainWindow->setMenuBar(menuBar);
- menuBar->addAction(menuFile->menuAction());
- menuBar->addAction(menuTest->menuAction());
- menuFile->addAction(actionOpen);
- menuFile->addAction(actionSave);
- menuTest->addAction(actionShow_Test_Dialog);
- menuTest->addAction(actionShow_Table);
- // 設置菜單項的具體回調函數
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::DirectoryOnly );
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::Default,
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::Question,
QMessageBox::Yes | QMessageBox::Default,
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("中文標簽") );
QString str;
str = QString::fromLocal8Bit(".....");
QLabel tLabel(str, 0);
53. 去除標題欄和邊框
:QWidget(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
在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