菜鸟玩qt(9)---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(":/p_w_picpaths/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(":/p_w_picpaths/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(":/p_w_picpaths/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(":/p_w_picpaths/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(":/p_w_picpaths/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(":/p_w_picpaths/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
十、Qt 4 for X11 OpenSource版如何静态连接?
答:编译安装的时候加上-static选项
Quote:
./configure -static   //必定要加static选项
gmake
gmake install

而后,在Makefile文件中加 static 选项或者在.pro文件中加上QMAKE_LFLAGS += -static,就能够链接静态库了。
十一、想在源代码中直接使用中文,而不使用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);
十二、为何将开发的使用数据库的程序发布到其它机器就链接不上数据库?
答:这是因为程序找不到数据库插件而致,可照以下解决方法:
在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部分

1三、如何建立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程序的写法,听从各平台级编译器所定的规则。
1四、如何启动一个外部程序
答:一、使用QProcess::startDetached()方法,启动外部程序后当即返回;
二、使用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();
1五、如何打印报表
答: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。
1六、如何在系统托盘区显示图标
答:在4.2及其以上版本中使用QSystemTrayIcon类来实现
1七、怎样将日志输出到文件中
答:(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。
1八、如何将图像编译到可执行程序中去
答:使用.qrc文件
写.qrc文件,例如:
res.qrc
Quote:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
   <file>p_w_picpaths/copy.png</file>
   <file>p_w_picpaths/cut.png</file>
   <file>p_w_picpaths/new.png</file>
   <file>p_w_picpaths/open.png</file>
   <file>p_w_picpaths/paste.png</file>
   <file>p_w_picpaths/save.png</file>
</qresource>
</RCC>

而后在.pro中加入下面代码:
Quote:
RESOURCES    = res.qrc
在程序中使用:
Quote:
...
:p_w_picpaths/copy.png
...
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
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 _p_w_picpath;
};
#endif

CPP文件: ImageWidget.cpp
Quote:
#include "ImageWidget.hpp"
ImageWidget::ImageWidget(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
_p_w_picpath.load("p_w_picpath/p_w_picpath_background");
setAutoFillBackground(true);   // 这个属性必定要设置
QPalette pal(palette());
pal.setBrush(QPalette::Window,
QBrush(_p_w_picpath.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(_p_w_picpath.scaled(event->size(), Qt::IgnoreAspectRatio,
Qt::SmoothTransformation)));
setPalette(pal);
}
2二、Windows下如何读串口信息
答:可经过注册表来读qt4.1.0 读取注册表获得 串口信息的方法!
23.
参考网址: http://www.ibm.com/developerworks/cn/linux/guitoolkit/qt/i18n/ QT程序国际化的过程 1.在全部须要采用双语或多语的地方采用QObject::tr("")将要显示的字符串包起来。   这里的字符串最好为英文,ASCII的编码在哪里都不会解码错。   tr()的做用之一是从.qm文件中取出与其所包含的内容对应的信息。   有些地方不宜采用tr(),好比定义某些变量使用的字符串,如:   static const char* strings[] = {T_TR_NOOP("Hello"),QT_TR_NOOP("World")};   能够采用QT_TR_NOOP() 和 QT_TRANSLATE_NOOP() 来标志它们。   前者用于单个字 符串,后者用于多个字符串。   若是要使用printf/sprintf之类的函数动态生成字符串,须要替换为arg(),如:   QString s = tr("Button %1").arg(i);