QT 常見技巧

來源:互聯網
上載者:User

本文是我前幾天一個網友告訴我的,當時看了感覺好,就儲存下來。今天再次查
看,感覺有必要把文章分享給各位學習QT 的朋友,因為網上好用的QT 資源真的
好少。
1、如果在表單關閉前自行判斷是否可關閉
答:重新實現這個表單的closeEvent()函數,加入判斷操作
Quote:
void MainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave())
{
writeSettings();
event->accept();
}
else
{
event->ignore();
}
}
2、如何用開啟和儲存檔案對話
答:使用QFileDialog
Quote:
QString fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty())
{
loadFile(fileName);
}
Quote:
QString fileName = QFileDialog::getSaveFileName(this);
if (fileName.isEmpty())
{
return false;
}
3、如果建立Actions(可在菜單和工具列裡使用這些Action)
答:
Quote:
newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
newAct->setShortcut(tr("Ctrl+N"));
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
openAct->setShortcut(tr("Ctrl+O"));
openAct->setStatusTip(tr("Open an existing file"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
saveAct->setShortcut(tr("Ctrl+S"));
saveAct->setStatusTip(tr("Save the document to disk"));
connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
saveAsAct = new QAction(tr("Save &As..."), this);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
cutAct->setShortcut(tr("Ctrl+X"));
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));
copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
copyAct->setShortcut(tr("Ctrl+C"));
copyAct->setStatusTip(tr("Copy the current selection's contents to the
"
"clipboard"));
connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));
pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
pasteAct->setShortcut(tr("Ctrl+V"));
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the
current "
"selection"));
connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Show the application's About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
4、如果建立主菜單
答:採用上面的QAction 的協助,建立主菜單
Quote:
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(newAct);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addAction(saveAsAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
editMenu = menuBar()->addMenu(tr("&Edit"));
editMenu->addAction(cutAct);
editMenu->addAction(copyAct);
editMenu->addAction(pasteAct);
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
5、如果建立工具列
答:採用上面的QAction 的協助,建立工具列
Quote:
fileToolBar = addToolBar(tr("File"));
fileToolBar->addAction(newAct);
fileToolBar->addAction(openAct);
fileToolBar->addAction(saveAct);
editToolBar = addToolBar(tr("Edit"));
editToolBar->addAction(cutAct);
editToolBar->addAction(copyAct);
editToolBar->addAction(pasteAct);
6、如何使用設定檔儲存配置
答:使用QSettings 類
Quote:
QSettings settings("Trolltech", "Application Example");
QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("size", QSize(400, 400)).toSize();
Quote:
QSettings settings("Trolltech", "Application Example");
settings.setValue("pos", pos());
settings.setValue("size", size());
7、如何使用警告、資訊等對話方塊
答:使用QMessageBox 類的靜態方法
Quote:
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;
8、如何使通用對話方塊中文化
答:對話方塊的中文化
比 如說,QColorDialog 的與文字相關的部分,主要在qcolordialog.cpp 檔案
中,我們可以從qcolordialog.cpp 用 lupdate 產生一個ts 檔案,然後用自定
義這個ts 檔案的翻譯,再用lrelease 產生一個.qm 檔案,當然了,主程式就要
改變要支援多國語言了, 使用這個.qm 檔案就可以了。
另外,還有一個更快的方法,在原始碼解開後有一個目錄translations,下面
有一些.ts, .qm 檔案,我們拷貝一個:
Quote:
cp src/translations/qt_untranslated.ts ./qt_zh_CN.ts
然 後,我們就用Linguist 開啟這個qt_zh_CN.ts,進行翻譯了,翻譯完成後,
儲存後,再用lrelease 命令產生qt_zh_CN.qm, 這樣,我們把它加入到我們的
qt project 中,那些系統的對話方塊,菜單等等其它的預設是英文的東西就能顯
示成中文了。
9、在Windows 下Qt 裡為什麼沒有終端輸出?
答:把下面的配置項加入到.pro 檔案中
Quote:
win32:CONFIG += console
10、Qt 4 for X11 OpenSource 版如何靜態連結?
答:編譯安裝的時候加上-static 選項
Quote:
./configure -static //一定要加static 選項
gmake
gmake install
然後,在Makefile 檔案中加 static 選項或者在.pro 檔案中加上QMAKE_LFLAGS
+= -static,就可以串連靜態庫了。
11、想在原始碼中直接使用中文,而不使用tr()函數進行轉換,怎麼辦?
答:在main 函數中加入下面三條語句,但並不提倡
Quote:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
或者
Quote:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
使用GBK 還是使用UTF-8,依源檔案中漢字使用的內碼而定
這樣,就可在源檔案中直接使用中文,比如:
Quote:
QMessageBox::information(NULL, "資訊", "關於本軟體的示範資訊",
QMessageBox::Ok, QMessageBox::NoButtons);
12、為什麼將開發的使用資料庫的程式發布到其它機器就串連不上資料庫?
答:這是由於程式找不到資料庫外掛程式而致,可照如下解決方案:
在main 函數中加入下面語句:
Quote:
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 模板
Quote:
TEMPLATE=lib
而源檔案則和使用普通的源檔案一樣,注意把標頭檔和源檔案分開,因為在其它
程式使用此DLL 時需要此標頭檔
在使用此DLL 時,則在此工程源檔案中引入DLL 標頭檔,並在.pro 檔案中加入
下面配置項:
Quote:
LIBS += -Lyourdlllibpath -lyourdlllibname
Windows 下和Linux 下同樣(Windows 下產生的DLL 檔案名稱為yourdlllibname.dll
而在Linux 下產生的為libyourdlllibname.so。注意,關於DLL 程式的寫法,
遵從各平台級編譯器所定的規則。
14、如何啟動一個外部程式
答:1、使用QProcess::startDetached()方法,啟動外部程式後立即返回;
2、使用QProcess::execute(),不過使用此方法時程式會最阻塞直到此方法執
行的程式結束後返回,這時候可使用QProcess 和QThread 這兩個類結合使用的
方法來處理,以防止在主線程中調用而導致阻塞的情況
先從QThread 繼承一個類,重新實現run()函數:
Quote:
class MyThread : public QThread
{
public:
void run();
};
void MyThread::run()
{
QProcess::execute("notepad.exe");
}
這樣,在使用的時候則可定義一個MyThread 類型的成員變數,使用時調用其
start()方法:
Quote:
class ...............
{...........
MyThread thread;
............
};
.....................
thread.start();
15、如何列印報表
答:Qt 目前對報表列印支援的庫還很少,不過有種變通的方法,就是使用
XML+XSLT+XSL-FO 來進行報表設計,XML 輸出資料,用XSLT 將XML 資料轉 換為
XSL-FO 格式的報表,由於現在的瀏覽器不直接支援XSL-FO 格式的顯示,所以暫
時可用工具(Apache FOP, Java 做的)將XSL-FO 轉換為PDF 文檔來進行列印,轉
換和列印由FOP 來做,產生XSL-FO 格式的報表可以由Qt 來產生,也可以由其它
內容轉換 過來,比如有工具(html2fo)將HTML 轉換為XSL-FO。
16、如何在系統托盤區顯示表徵圖
答:在4.2 及其以上版本中使用QSystemTrayIcon 類來實現
17、怎樣將日誌輸出到檔案中
答:(myer 提供)
Quote:
void myMessageOutput( QtMsgType type, const char *msg )
{
switch ( type ) {
case QtDebugMsg:
//寫入檔案;
break;
case QtWarningMsg:
break;
case QtFatalMsg:
abort();
}
}
int main( int argc, char** argv )
{
QApplication app( argc, argv );
qInstallMsgHandler( myMessageOutput );
......
return app.exec();
}
qDebug(), qWarning(), qFatal()分別對應以上三種type。
18、如何將映像編譯到可執行程式中去
答:使用.qrc 檔案
寫.qrc 檔案,例如:
res.qrc
Quote:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/copy.png</file>
<file>images/cut.png</file>
<file>images/new.png</file>
<file>images/open.png</file>
<file>images/paste.png</file>
<file>images/save.png</file>
</qresource>
</RCC>
然後在.pro 中加入下面代碼:
Quote:
RESOURCES = res.qrc
在程式中使用:
Quote:
...
:images/copy.png
...
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
Quote:
#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
Quote:
#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 讀取註冊表得到 串口資訊的方法!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.