qt技巧.docx
- 文档编号:17860094
- 上传时间:2023-08-04
- 格式:DOCX
- 页数:20
- 大小:27.64KB
qt技巧.docx
《qt技巧.docx》由会员分享,可在线阅读,更多相关《qt技巧.docx(20页珍藏版)》请在冰点文库上搜索。
qt技巧
1、如果在窗体关闭前自行判断是否可关闭
答:
重新实现这个窗体的closeEvent()函数,加入判断操作
voidMainWindow:
:
closeEvent(QCloseEvent*event)
{
if(maybeSave())
{
writeSettings();
event->accept();
}
else
{
event->ignore();
}
}
2、如何用打开和保存文件对话框
答:
使用QFileDialog
QStringfileName=QFileDialog:
:
getOpenFileName(this);
if(!
fileName.isEmpty())
{
loadFile(fileName);
}
QStringfileName=QFileDialog:
:
getSaveFileName(this);
if(fileName.isEmpty())
{
returnfalse;
}
如果用qt自带的话:
选择文件夹
QFileDialog*openFilePath=newQFileDialog(this,"请选择文件夹","file");//打开一个目录选择对话框
openFilePath->setFileMode(QFileDialog:
:
DirectoryOnly);
if(openFilePath->exec()==QDialog:
:
Accepted)
{
//codehere!
}
deleteopenFilePath;
选择文件:
QFileDialog*openFilePath=newQFileDialog(this);
openFilePath->setWindowTitle(tr("请选择文件"));
openFilePath->setDirectory(".");
openFilePath->setFilter(tr("txtorimage(*.jpg*.png*.bmp*.tiff*.jpeg*.txt)"));
if(openFilePath->exec()==QDialog:
:
Accepted)
{
//codehere
}
deleteopenFilePath;
7、如何使用警告、信息等对话框
答:
使用QMessageBox类的静态方法
intret=QMessageBox:
:
warning(this,tr("Application"),
tr("Thedocumenthasbeenmodified./n"
"Doyouwanttosaveyourchanges?
"),
QMessageBox:
:
Yes|QMessageBox:
:
Default,
QMessageBox:
:
No,
QMessageBox:
:
Cancel|QMessageBox:
:
Escape);
if(ret==QMessageBox:
:
Yes)
returnsave();
elseif(ret==QMessageBox:
:
Cancel)
returnfalse;
或者简单点儿:
QMessageBox:
:
information(this,"关于","盲人辅助系统(管理端)!
/nVersion:
1.0/nNoCopyright");
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文件里,详细情况情参考QtDocumentReference里的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()函数:
classMyThread:
publicQThread
{
public:
voidrun();
};
voidMyThread:
:
run()
{
QProcess:
:
execute("notepad.exe");
}
这样,在使用的时候则可定义一个MyThread类型的成员变量,使用时调用其start()方法:
class...............
{...........
MyThreadthread;
............
};
.....................
thread.start();
19、如何制作不规则形状的窗体或部件
答:
请参考下面的帖子
http:
//www.qtcn.org/bbs/read.php?
tid=8681
20、删除数据库时出现"QSqlDatabasePrivate:
:
removeDatabase:
connection'xxxx'isstillinuse,allquerieswillceasetowork"该如何处理
答:
出现此种错误是因为使用了连接名字为xxxx的变量作用域没有结束,解决方法是在所有使用了xxxx连接的数据库组件变量的作用域都结束后再使用QSqlDatabase:
:
removeDatabae("xxxx")来删除连接。
21、如何显示一个图片并使其随窗体同步缩放
答:
下面给出一个从QWidget派生的类ImageWidget,来设置其背景为一个图片,并可随着窗体改变而改变,其实从下面的代码中可以引申出其它许多方法,如果需要的话,可以从这个类再派生出其它类来使用。
头文件:
ImageWidget.hpp
#ifndefIMAGEWIDGET_HPP
#defineIMAGEWIDGET_HPP
#include
#include
classImageWidget:
publicQWidget
{
Q_OBJECT
public:
ImageWidget(QWidget*parent=0,Qt:
:
WindowFlagsf=0);
virtual~ImageWidget();
protected:
voidresizeEvent(QResizeEvent*event);
private:
QImage_image;
};
#endif
CPP文件:
ImageWidget.cpp
#include"ImageWidget.hpp"
ImageWidget:
:
ImageWidget(QWidget*parent,Qt:
:
WindowFlagsf)
:
QWidget(parent,f)
{
_image.load("image/image_background");
setAutoFillBackground(true);//这个属性一定要设置
QPalettepal(palette());
pal.setBrush(QPalette:
:
Window,
QBrush(_image.scaled(size(),Qt:
:
IgnoreAspectRatio,
Qt:
:
SmoothTransformation)));
setPalette(pal);
}
ImageWidget:
:
~ImageWidget()
{
}
//随着窗体变化而设置背景
voidImageWidget:
:
resizeEvent(QResizeEvent*event)
{
QWidget:
:
resizeEvent(event);
QPalettepal(palette());
pal.setBrush(QPalette:
:
Window,
QBrush(_image.scaled(event->size(),Qt:
:
IgnoreAspectRatio,
Qt:
:
SmoothTransformation)));
setPalette(pal);
}
22、Windows下如何读串口信息
答:
可通过注册表来读qt4.1.0读取注册表得到串口信息的方法!
23.背景修改
QStringfilename="E:
/图片/壁纸/1.jpg";
QPixmappixmap(filename);
pal.setBrush(QPalette:
:
Window,QBrush(pixmap));
setPalette(pal);
24.载入某个指定类型文件
openFileName=QFileDialog:
:
getOpenFileName(this,tr("OpenImage"),"/home/picture",tr("ImageFiles(*.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
26.图片问题
用label就可以载入图片,方法:
label->setPixmap(QPixmap(“path(可以用geifilename函数得到)”));
但是这样的label没有滚动条,很不灵活,可以这样处理:
在QtDesign中创建一个QScrollArea控件,设置一些属性,然后在代码中新建一个label指针,在cpp的构造函数中用newQLabel(this)初始化(一定要有this,不然后面setWidget会出错)。
然后再:
scrollArea->setWidget(label_2);
scrollArea->show();
27.布局
最后要充满窗口,点击最外层的窗口空白处。
再点击水平layout即可
28.程序图标
准备一个ICO图标,把这个图标复制到程序的主目录下,姑且名字叫”myicon.ico”吧。
然后编写一个icon.rc文件。
里面只有一行文字:
IDI_ICON1ICON“myicon.ico”
最后,在工程的pro文件里加入一行:
RC_FILE=icon.rc
qmake和make一下,就可以发现你的应用程序拥有漂亮的图标了。
29.回车输出
QT中操作文件,从文件流QTextStream输出回车到txt的方法是<<'r'< 30.QListView的添加或者删除 QStringListuser; user+="first"; user+="second"; QStringListModel*model=newQStringListModel(user); userList->setModel(model);//useList是个QListView user+="third"; model->setStringList(user); 31.设置背景音乐 如果只是简单的设置背景音乐的话。 用QSound。 具体查看qt助手。 windows下的QSound只能播放wav格式哦。 。 32.禁止QAbstractItemView的子类的双击修改功能。 比如listview,双击某个item就会成为编辑模式。 禁止此功能。 用: QAbstractItemVIew`sname->setEditTriggers(QAbstractItemView: : NoEditTriggers); 33.qt对文件的操作 读文件 QFileinputFile(": /forms/input.txt"); inputFile.open(QIODevice: : ReadOnly); QTextStreamin(&inputFile); QStringline=in.readAll(); inputFile.close(); 写文件 QFilefile(filename); if(! file.open(QIODevice: : WriteOnly)) { fprintf(stderr,"Couldnotopen%sforwriting: %s/n", qPrintable(filename), qPrintable(file.errorString())); returnfalse; } file.write(data->readAll()); file.close(); 将某个路径转化为当前系统认可的路径 QDir: : convertSeparators(openFileName) 获取当前路径 QDircurrentPath; QStringfilePath=currentPath.absolutePath(); QStringpath=QDir: : convertSeparators(filePath+"/"+clickedClass); 一些操作 QFile: : exists(fileName) QFile: : Remove(); 文件打开模式 if(file.open(QIODevice: : WriteOnly|QIODevice: : Append|QIODevice: : ReadOnly) 34.qt确认对话框 QMessageBoxmb(tr("删除确认"),tr("确认删除此项? "), QMessageBox: : Question, QMessageBox: : Yes|QMessageBox: : Default, QMessageBox: : No|QMessageBox: : Escape, QMessageBox: : NoButton); if(mb.exec()==QMessageBox: : No) return; 35.QListView QStringListuser; user+="first"; user+="second"; QStringListModel*model=newQStringListModel(user); QListViewuser_id->setModel(model); user+="third";//下面2步是更新 model->setStringList(user); 36.允许这样的语句: Layout->setGeometry(QRect(10,10,100,50));QHBoxLayout等布局对象(butnotwidget)里的Widget的排列,是按其加入的先后顺序而定的。 要让其显示在一个窗口上,需要把让这个窗口作为其Parent. 37.setMargin()setsthewidthoftheouterborder.ThisisthewidthofthereservedspacealongeachoftheQBoxLayout'sfoursides.就是设置其周围的空白距离。 38.setSpacing()setsthewidthbetweenneighboringboxes.(YoucanuseaddSpacing()togetmorespaceataparticularspot.)就是设置相邻对象间的距离。 39.addStretch()tocreateanempty,stretchablebox.相当于加入了一个空白的不显示的部件。 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的方法,而不是用的WindowsAPI) 41.使用以下代码可以为一个窗口部件加入背景图片: QPixmappic; pic.load("qqpet.bmp"); Label.setPixmap(pic); Label.show(); QpushButton也可以。 但是在使用了setPixmap后,原来的文字就显示不了了。 如果在setPixmap后设置文字,则图片就显示不了。 其他事项: theconstructorofQPixmap()aceptchar*onlyforxpmimage. hopefileisplacedproperandisbmp.jpg'sgif'scancauseerror(configure).----不能缩放图象。 42.调用voidQWidget: : setFocus()[virtualslot]即可设置一个焦点到一个物体上。 43.让窗口保持固定大小: main_window->setMinimumSize(g_main_window_w,g_main_window_h); main_window->setMaximumSize(g_main_window_w,g_main_window_h); 只要让最小尺寸和最大尺寸相等即可。 44.获得系统日期: QDateDate=QDate: : currentDate(); intyear=Date.year(); intmonth=Date.month(); intday=Date.day(); 45.获得系统时间: QTimeTime=QTime: : currentTime(); inthour=Time.hour(); intminute=Time.minute(); intsecond=Time.second(); 46.QString: : number可以直接传其一个数而返回一个QString对象。 因此可以用以下代码: m_textedit->setText(QString: : number(10)); 47.利用QString: : toInt()之类的接口可以转换字符串为数。 这就可以把QLineEdit之类返回的内容转换格式。 文档里的描述: intQString: : toInt(bool*ok=0,intbase=10)
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- qt 技巧
![提示](https://static.bingdoc.com/images/bang_tan.gif)