原博網址: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
若是用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()方法:
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("中文標籤") );