常见的几个C++ QT4问题的处理

1、如果在窗体关闭前自行判断是否可关闭
答:重新实现这个窗体的closeEvent()函数,加入判断操作
  1. void MainWindow::closeEvent(QCloseEvent *event)
  2. {
  3.        if (maybeSave())
  4.        {
  5.               writeSettings();
  6.               event->accept();
  7.        }
  8.        else
  9.        {
  10.               event->ignore();
  11.        }
  12. }
复制代码
2、如何用打开和保存文件对话
答:使用QFileDialog
  1.               QString fileName = QFileDialog::getOpenFileName(this);
  2.               if (!fileName.isEmpty())
  3.               {
  4.                      loadFile(fileName);
  5.               }
复制代码
  1.        QString fileName = QFileDialog::getSaveFileName(this);
  2.        if (fileName.isEmpty())
  3.        {
  4.               return false;
  5.        }
复制代码
3、如果创建Actions(可在菜单和工具栏里使用这些Action)
答:
  1. newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
  2.         newAct->setShortcut(tr("Ctrl+N"));
  3.         newAct->setStatusTip(tr("Create a new file"));
  4.         connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

  5.         openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
  6.         openAct->setShortcut(tr("Ctrl+O"));
  7.         openAct->setStatusTip(tr("Open an existing file"));
  8.         connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

  9.         saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
  10.         saveAct->setShortcut(tr("Ctrl+S"));
  11.         saveAct->setStatusTip(tr("Save the document to disk"));
  12.         connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));

  13.         saveAsAct = new QAction(tr("Save &As..."), this);
  14.         saveAsAct->setStatusTip(tr("Save the document under a new name"));
  15.         connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));

  16.         exitAct = new QAction(tr("E&xit"), this);
  17.         exitAct->setShortcut(tr("Ctrl+Q"));
  18.         exitAct->setStatusTip(tr("Exit the application"));
  19.         connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

  20.         cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
  21.         cutAct->setShortcut(tr("Ctrl+X"));
  22.         cutAct->setStatusTip(tr("Cut the current selection's contents to the "
  23.                                 "clipboard"));
  24.         connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));

  25.         copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
  26.         copyAct->setShortcut(tr("Ctrl+C"));
  27.         copyAct->setStatusTip(tr("Copy the current selection's contents to the "
  28.                                  "clipboard"));
  29.         connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));

  30.         pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
  31.         pasteAct->setShortcut(tr("Ctrl+V"));
  32.         pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
  33.                                   "selection"));
  34.         connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));

  35.         aboutAct = new QAction(tr("&About"), this);
  36.         aboutAct->setStatusTip(tr("Show the application's About box"));
  37.         connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

  38.         aboutQtAct = new QAction(tr("About &Qt"), this);
  39.         aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
  40.         connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
复制代码
4、如果创建主菜单
答:采用上面的QAction的帮助,创建主菜单
  1.        fileMenu = menuBar()->addMenu(tr("&File"));
  2.         fileMenu->addAction(newAct);
  3.         fileMenu->addAction(openAct);
  4.         fileMenu->addAction(saveAct);
  5.         fileMenu->addAction(saveAsAct);
  6.         fileMenu->addSeparator();
  7.         fileMenu->addAction(exitAct);

  8.         editMenu = menuBar()->addMenu(tr("&Edit"));
  9.         editMenu->addAction(cutAct);
  10.         editMenu->addAction(copyAct);
  11.         editMenu->addAction(pasteAct);

  12.         menuBar()->addSeparator();

  13.         helpMenu = menuBar()->addMenu(tr("&Help"));
  14.         helpMenu->addAction(aboutAct);
  15.         helpMenu->addAction(aboutQtAct);
复制代码
5、如果创建工具栏
答:采用上面的QAction的帮助,创建工具栏
  1.        fileToolBar = addToolBar(tr("File"));
  2.         fileToolBar->addAction(newAct);
  3.         fileToolBar->addAction(openAct);
  4.         fileToolBar->addAction(saveAct);

  5.         editToolBar = addToolBar(tr("Edit"));
  6.         editToolBar->addAction(cutAct);
  7.         editToolBar->addAction(copyAct);
  8.         editToolBar->addAction(pasteAct);
复制代码
6、如何使用配置文件保存配置
答:使用QSettings类
  1.        QSettings settings("Trolltech", "Application Example");
  2.         QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
  3.         QSize size = settings.value("size", QSize(400, 400)).toSize();
复制代码
  1.       QSettings settings("Trolltech", "Application Example");
  2.         settings.setValue("pos", pos());
  3.         settings.setValue("size", size());
复制代码
7、如何使用警告、信息等对话框
答:使用QMessageBox类的静态方法
  1. int ret = QMessageBox::warning(this, tr("Application"),
  2.                          tr("The document has been modified.\n"
  3.                             "Do you want to save your changes?"),
  4.                          QMessageBox::Yes | QMessageBox::Default,
  5.                          QMessageBox::No,
  6.                          QMessageBox::Cancel | QMessageBox::Escape);
  7.             if (ret == QMessageBox::Yes)
  8.                 return save();
  9.             else if (ret == QMessageBox::Cancel)
  10.                 return false;
复制代码
8、如何使通用对话框中文化
答:对话框的中文化
比如说,QColorDialog的与文字相关的部分,主要在 qcolordialog.cpp文件中,我们可以从qcolordialog.cpp用 lupdate生成一个ts文件,然后用自定义这个ts文件的翻译,再用lrelease生成一个.qm文件,当然了,主程序就要改变要支持多国语言了,使用这个.qm文件就可以了。

另外,还有一个更快的方法,在源代码解开后有一个目录translations,下面有一些.ts, .qm文件,我们拷贝一个:
  1. 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文件中
  1. win32:CONFIG += console
复制代码
10、Qt 4 for X11 OpenSource版如何静态链接?
答:编译安装的时候加上-static选项
  1. ./configure -static   //一定要加static选项
  2. gmake
  3. gmake install
复制代码
然后,在Makefile文件中加 static 选项或者在.pro文件中加上QMAKE_LFLAGS += -static,就可以连接静态库了。

11、想在源代码中直接使用中文,而不使用tr()函数进行转换,怎么办?
答:在main函数中加入下面三条语句,但并不提倡
  1. QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
  2. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  3. QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
复制代码
或者
  1. QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
  2. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
  3. QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
复制代码
使用GBK还是使用UTF-8,依源文件中汉字使用的内码而定
这样,就可在源文件中直接使用中文,比如:
  1. QMessageBox::information(NULL, "信息", "关于本软件的演示信息", QMessageBox::Ok, QMessageBox::NoButtons);
复制代码
12、为什么将开发的使用数据库的程序发布到其它机器就连接不上数据库?
答:这是由于程序找不到数据库插件而致,可照如下解决方法:
在main函数中加入下面语句:
  1. 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模板
  1. TEMPLATE=lib
复制代码
而源文件则和使用普通的源文件一样,注意把头文件和源文件分开,因为在其它程序使用此DLL时需要此头文件
在使用此DLL时,则在此工程源文件中引入DLL头文件,并在.pro文件中加入下面配置项:
  1. LIBS += -Lyourdlllibpath -lyourdlllibname
复制代码
Windows下和Linux下同样(Windows下生成的DLL文件名为yourdlllibname.dll而在Linux下生成的为libyourdlllibname.so。注意,关于DLL程序的写法,遵从各平台级编译器所定的规则。

14、如何启动一个外部程序
答:
1、使用QProcess::startDetached()方法,启动外部程序后立即返回;
2、使用QProcess::execute(),不过使用此方法时程序会最阻塞直到此方法执行的程序结束后返回,这时候可使用QProcess和QThread这两个类结合使用的方法来处理,以防止在主线程中调用而导致阻塞的情况
先从QThread继承一个类,重新实现run()函数:
  1. class MyThread : public QThread
  2. {
  3. public:
  4.      void run();
  5. };

  6. void MyThread::run()
  7. {
  8.     QProcess::execute("notepad.exe");
  9. }
复制代码
这样,在使用的时候则可定义一个MyThread类型的成员变量,使用时调用其start()方法:
  1. class ...............
  2. {...........
  3. MyThread thread;
  4. ............
  5. };

  6. .....................
  7. 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、怎样将日志输出到文件中
答:
  1. void myMessageOutput( QtMsgType type, const char *msg )
  2. {
  3.     switch ( type ) {
  4.         case QtDebugMsg:
  5.             //写入文件;
  6.             break;
  7.         case QtWarningMsg:
  8.             break;
  9.         case QtFatalMsg:
  10.             abort();
  11.     }
  12. }

  13. int main( int argc, char** argv )
  14. {
  15.     QApplication app( argc, argv );
  16.     qInstallMsgHandler( myMessageOutput );
  17.     ......
  18.     return app.exec();
  19. }
复制代码
qDebug(), qWarning(), qFatal()分别对应以上三种type。

18、如何将图像编译到可执行程序中去
答:使用.qrc文件
写.qrc文件,例如:
res.qrc
  1. <!DOCTYPE RCC><RCC version="1.0">
  2. <qresource>
  3.      <file>images/copy.png</file>
  4.      <file>images/cut.png</file>
  5.      <file>images/new.png</file>
  6.      <file>images/open.png</file>
  7.      <file>images/paste.png</file>
  8.      <file>images/save.png</file>
  9. </qresource>
  10. </RCC>
复制代码
然后在.pro中加入下面代码:
  1. RESOURCES     = res.qrc
复制代码
在程序中使用:
  1. ...
  2. :images/copy.png
  3. ...
复制代码
19、删除数据库时出现"QSqlDatabasePrivate::removeDatabase: connection 'xxxx' is still in use, all queries will cease to work"该如何处理
答:出现此种错误是因为使用了连接名字为xxxx的变量作用域没有结束,解决方法是在所有使用了xxxx连接的数据库组件变量的作用域都结束后再使用QSqlDatabase::removeDatabae("xxxx")来删除连接。

20、如何显示一个图片并使其随窗体同步缩放
答:下面给出一个从QWidget派生的类ImageWidget,来设置其背景为一个图片,并可随着窗体改变而改变,其实从下面的代码中可以引申出其它许多方法,如果需要的话,可以从这个类再派生出其它类来使用。
头文件: ImageWidget.hpp
  1. #ifndef IMAGEWIDGET_HPP
  2. #define IMAGEWIDGET_HPP

  3. #include <QtCore>
  4. #include <QtGui>

  5. class ImageWidget : public QWidget
  6. {
  7.     Q_OBJECT
  8. public:
  9.     ImageWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
  10.     virtual ~ImageWidget();
  11. protected:
  12.     void resizeEvent(QResizeEvent *event);
  13. private:
  14.     QImage _image;
  15. };

  16. #endif
复制代码
CPP文件: ImageWidget.cpp
  1. #include "ImageWidget.hpp"

  2. ImageWidget::ImageWidget(QWidget *parent, Qt::WindowFlags f)
  3.     : QWidget(parent, f)
  4. {
  5.     _image.load("image/image_background");
  6.     setAutoFillBackground(true);   // 这个属性一定要设置
  7.     QPalette pal(palette());
  8.     pal.setBrush(QPalette::Window,
  9.                 QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio,
  10.                         Qt::SmoothTransformation)));
  11.     setPalette(pal);
  12. }

  13. ImageWidget::~ImageWidget()
  14. {
  15. }

  16. // 随着窗体变化而设置背景
  17. void ImageWidget::resizeEvent(QResizeEvent *event)
  18. {
  19.     QWidget::resizeEvent(event);
  20.     QPalette pal(palette());
  21.     pal.setBrush(QPalette::Window,
  22.                 QBrush(_image.scaled(event->size(), Qt::IgnoreAspectRatio,
  23.                         Qt::SmoothTransformation)));
  24.     setPalette(pal);
  25. }
复制代码
21、如何使用WebKit查看的网页进入编辑状态
答:在你的HTML网页代码的HTML元素节点上增加一个属性contenteditable就可以使QWebView中查看的网页进入编辑状态了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值