qt4和vs2010

13 篇文章 0 订阅


转自:http://blog.csdn.net/fengyu09/article/details/8765887


英文原文: http://www.michaelboeni.net/?p=355

First steps: Qt4 and Visual Studio 2010

 

Developers usually prefer to stick to an IDE once they know it well. I am no different. Using the Qt IDE (Qt Creator) is all nice and proper but I have a perfectly tuned MS Visual Studio 2010 environment and want to stick with that. In my first two posts on Qt I covered compilation issues with the Qt library and integration problems with the Add-In.

Making the first few steps with Qt using MSVS is not that easy, as Qt brings forth a few new (but extremely powerful) concepts. Once you have mastered these basic concepts, you can take off with Qt 

Okay, this is the setup so far:
MS Visual Studio 2010 Ultimate (on Win 7, 32 Bit)
Qt Version 4.7 compiled for MSVS 2010
Qt Add-In Version 1.1.6 for MSVS

This post will cover on how to create an app using the Add-In and solving a first few potential pitfalls:
Using the Add-In Wizard in MSVS to create a “Qt Application”
Designing the UI using Qt Designer
Accessing UI components in your code
Adding custom Slots to your application (The signals & slots thingy)

开发者一旦认为某个IDE好用,就会偏向迷恋使用它。我也不例外。使用Qt IDE(Qt Creator)非常美好而且适合,但是我非常喜欢微软的vs2010环境,而且喜欢跟随它。在我前两个关于Qt的帖子里,描述了使用Qt库编译问题和使用Add-In集成问题。

开始在msvs里使用Qt并不是很容易的事,因为Qt带来了超前的几个新理念(也非常强大)。在你掌握了这些基本原理后,你就能使用Qt起飞了。

好吧,下面是目前的设置:

vs2010 旗舰版(win7 32位)

Qt Version 4.7 compiled for MSVS 2010 ----------或5.0.1
Qt Add-In Version 1.1.6 for MSVS--------------------或 1.2.0

本文将阐述如何使用插件创建一个App,并解决开始几个有可能存在的陷阱:

使用msvs里的Qt插件向导创建一个"Qt应用程序"

使用Qt 设计师设计UI界面

在代码里访问UI组件

在应用程序里添加自定义槽(信号和槽物件)。

 

Create a Qt Application using the Add-In

The Qt Add-In is integrated into the MSVS UI in several ways. You have special wizards at your disposal that let you create the most common types of Qt projects and you have a “Qt” menu entry which offers import/export functionality and some options. As I have started my Qt app from scratch using MSVS and the Add-In, I have not used many of the functions there. The only exceptions are “Launch Designer” and “Launch Linguist”, although I usually start the Designer by double-clicking on the “.ui” file in the solution explorer.

To create a new App using the wizard, do the following:
1.       Navigate to “File -> New -> Project”

The project wizard will open:

使用插件创建Qt应用程序

把Qt插件集成到msvs用户界面有几种方法。随时听从你吩咐的特殊向导帮助你创建大多数通用种类的Qt项目,而且你有一个Qt菜单项,它提供了导入/导出和一些选项。因为我是使用msvs和插件从零开始我的Qt程序,所以我没有使用那里的很多功能。仅有的例外是 “Launch Designer” 和 "Launch Linguist”,然而我通常是在解决方案浏览器里双击".ui"文件打开Qt设计师。

通过向导创建一个新应用,如下做:

1、文件->新建->项目

项目向导会打开:

 

2.       Select a project type (“Qt Application” in this case), enter a project name (I used "SampleApp") and press OK

The Qt-Part of the wizard is started and will present you with a “welcome” page, a “project settings” page and a “Generated Class” page. On the “project settings” page, you are able to select the Qt modules you wish to include in your project. “Core Library” and “GUI Library” are always selected by default. This is how it looks:

2、选择一个项目类型(本例使用"Qt Application"),键入一个项目名字(我使用 "SampleApp"),然后按 OK。

向导的Qt部分会启动,为你呈现:1个欢迎页,1个项目设置页和1个生成的类页。在项目设置页面,你可以选择希望包含在你的项目中的Qt模块。“Core Library” 和"GUI Library”总是默认被选择。这是它看起来的样子:

Note: If you forget to choose a library in the wizard, don’t worry! You can change the libraries to be included later: Just navigate to the Qt menu item and select “Qt Project Settings”. There you can add or remove libraries as you please.
3.       Click next to get to the “Generated Classes” page

注:如果你在向导里忘记选择一个库,不必担心!在以后你能修改被包含的库:只是找到Qt菜单项并选择"Qt Project Settings->Qt modules",那里你可以根据个人高兴增加或移除库。

3、点击 next到 生成的类页面

 

The “Generated Classes” page lets you tweak the names of your project files, choose the base class, add a default application icon or choose to use precompiled headers. I have chosen to add the default application icon in this case. It is not critical though, you can always add a custom one later (perhaps to be covered in another tutorial).

You can leave the base class at its default setting “QMainWindow”.
4.       Click finish to have the Add-In create your project and prepare the IDE.

The solution explorer in MS Visual Studio should now look like this:

生成的类页面让你调整你的项目文件的名字,选择基础类,增加一个缺省程序图标或选择使用预编译的头文件。在本例中我选择增加缺省应用程序图标。它不是只有一次添加的机会,你永远可以在以后添加一个(也许会在另一个教程里讲述)。

4、点击 Finish,Qt插件会创建你的项目并准备IDE。

vs2010的解决方案浏览器看起来像这个样子:

 

This is all you need for step one. Building and starting the App should give you a simple window that looks like this:

这是第1步你需要做的所有事。编译和启动程序,会看到一个简单的窗口,看起来像这样:

 

 

Designing the UI using Qt Designer

Qt Designer is “loosely” integrated into MS Visual Studio as it will open Designer externally. You can start Qt Designer by navigating to the Qt menu and selecting “Launch Designer” or by double-clicking the “.ui” file in your solution explorer (my preferred way).
1.       Double click on “sampleapp.ui” in your solution designer

Designer will look like this:

使用Qt Designer设计UI

Qt Designer是松散的集成在MS Visual Studio里的,因为它会在外面打开设计师。启动MS Visual Studio有两种方式:可以在Qt菜单里选择“Launch Designer”,或者在你的解决方案浏览器里双击 ".ui"文件(我喜欢的方式)。

1、在方案浏览器里双击"sampleapp.ui”

设计师看起来是这个样子:

Note: The number of widgets you get in the widget box (to the left) depends on the options you used when compiling the library (i.e. having added the WebKit, Phonon, etc.). If you have used the parameters from my earlier tutorials, you should have a pretty complete set of widgets like it is shown above.
2.       Now navigate to the “TextEdit” widget (you will find it under the “Input Widgets” heading in the widget box). Drag it to our form and drop it somewhere onto the central area of our user interface.

Your form should look like this:

注:左侧组件盒子里,你得到的部件的数量依赖于编译这个库时你使用的选项(如,增加了WebKit,Phonon等)。如果你曾使用了我前面教程里的参数,你会拥有一套如上显示的非常完整的部件集合。

2、找到 TextEdit部件(部件盒子里,你会在标有 Input Widgets下面找到它)。把它拖曳到窗体上,并把它放到我们的用户界面的近似中央位置。

你的窗体看起来是这样:

 

3.       Now right-click anywhere on the central widget (not on the TextEdit widget you just dropped there) and choose “Layout -> Layout in a Grid”

This will stretch the TextEdit widget to cover the whole central area of our UI.

Note: You could have used vertical or horizontal layout as well. The main goal here is to have the TextEdit widget fill the entire central area and all mentioned layouts would have achieved this. I will not go deeper with layouts here 

We will now add a menu entry and one menu item under it
4.       Double-click on the area named “Type Here” in the menu bar of our UI, type “Do Something” and press enter
5.       Now double-click the “Type Here” in the drop down area that just opened underneath our “Do Something” menu entry, type “Do Thing A” and press enter

Your UI should look like this:

 

3、现在在中央部件的任何地方右键点击(不是在你刚放的TextEdit部件上),选择 布局->网格布局。这会拉伸TextEdit部件,使它覆盖我们的UI的整个中央区域。

注:你也可以使用垂直或水平布局。这里的主要目标是让TextEdit部件填满整个中央区域,而且所有提到的布局也会实现同类效果。我不准备在这里深入讨论布局。

我们会增加一个菜单入口,并在它下面增加一个菜单项。

4、在我们的UI的菜单条上,有个区域写着“在这里输入”,双击此处,写上"Do Something",然后按回车键。

5、现在“Do Something”菜单入口下面刚打开的下拉区域,双击“在这里输入”,键入"Do Thing A“并按回车键。

你的UI应当是这个样子:

 

Now something interesting has happened: When you have added the “Do Thing A” menu item, Designer has automatically created a “QAction”. Actions are a very convenient way to add functionality to your UI. You can, for example, define a QAction “newDocument” which you then add to the main menu, the toolbar using a nice icon and create a keyboard shortcut for your hardcore users. All these different ways of using the UI (clicking a menu entry, clicking an icon on a toolbar or typing a keyboard shortcut) will all trigger the same QAction.

You will find the action I just mentioned in the lower right corner of Designer under “Action Editor”. Double-click the entry in the Action Editor to change its details. You can, for example, add an icon to the action which will be shown wherever you use your QAction, very convenient. We will leave the settings as they are, though.

Note: You can add a “shortcut key” to a menu item. If you add an ampersand “&” in the menu name, the following character will serve as a shortcut for that entry. For example, if you enter “&Do Something”, then “Alt-D” will open the “Do Something” menu.
6.       That’s all we will do in Designer for now. Save your UI and close Designer.

现在有趣的事情发生了:在你添加了“Do Thing A”菜单项以后,设计师自动地创建一个“QAction”。Actions是一个很方便的办法以增加功能到你的UI。比如,你能定义一个QAction “newDocument”,然后你把它加到主菜单,工具栏使用一个漂亮的图标,并为你的核心用户创建一个键盘快捷方式。所有这些使用UI的不同方法(点击一个菜单项,点击工具栏上的图标或者按下键盘快捷方式)都会触发相同的QAction。

你会发现我刚才提到的位于设计师右下角的"动作编辑器"下面的action,双击这个项以修改它的细节。譬如,你可以为这个动作添加一个图标,在你使用QAction的任何地方它都会显示,非常方便。当然,我们将保留他们原来的设置不做改变。

注:你可以为菜单项添加一个“快捷键”。如果你在菜单名增加一个与符号“&”,这个后面跟随的字符会作为那一项的快捷键。如,如果你键入“&Do Something”,那么 “Alt-D” 将会打开"Do Something” 菜单。

6、这是我们在设计师里所做的全部工作。保存你的UI并关闭设计师。

Accessing UI components in your code

Now we are ready to add functionality to the application. As the Add-In has done most of the preparations, just a few little steps are left to make the UI components accessible in the code. Qt offers three ways of using an UI file from Designer in your code: the “Direct” approach, single inheritance and multiple inheritance. This is a very important choice and depends a lot on what you want to achieve with your user interface. I strongly recommend reading the following tutorial from Trolltech/Nokia: Using a Designer UI File in Your Application.

For this tutorial (and also my own applications) I have chosen to follow the multiple inheritance approach. We need to make two major changes to our code to switch our app to the multiple inheritance approach:
1.       In MSVS, double-click “sampleapp.h” to open it in the editor

It should look like this:

在代码里访问UI组件

现在我们为程序添加功能。因为插件已经做了大部分准备工作,只需要很少的步骤就能在代码里访问UI组件。Qt提供3种方法在你的代码里使用来自设计师的UI文件:“直接”方法,单个继承和多个继承。这个非常重要,并主要取决于你想从你的用户界面获取什么。我强烈建议你阅读来自Trolltech/Nokia的教程:在你的程序里使用设计师UI文件

在这个教程里(而且我自己的程序)我选择了遵从多个继承的方法。我们需要在代码里做两个主要的修改,以把我们的程序切换到多继承的方法:

1、在msvs,双击"sampleapp.h”,在编辑器里打开它。

它的样子如下:

 

[cpp]  view plain copy
  1. #ifndef SAMPLEAPP_H  
  2. #define SAMPLEAPP_H  
  3. #include "QtGui/QMainWindow";  
  4. #include "ui_sampleapp.h";  
  5.    
  6. class SampleApp : public QMainWindow  
  7. {  
  8.    Q_OBJECT  
  9.    
  10.    public:  
  11.      SampleApp(QWidget *parent = 0, Qt::WFlags flags = 0);  
  12.      ~SampleApp();  
  13.    
  14.    private:  
  15.      Ui::SampleAppClass ui;  
  16. };  
  17.    
  18. #endif // SAMPLEAPP_H  

 

2.       Change the code to make it inherit from QMainWindow AND SampleAppClass

Your code will now look like this.

2、改变代码使它继承自 QMainWindow 和SampleAppClass。

代码样子如下:

 

[cpp]  view plain copy
  1. #ifndef SAMPLEAPP_H  
  2. #define SAMPLEAPP_H  
  3. #include "QtGui/QMainWindow";  
  4. #include "ui_sampleapp.h";  
  5.    
  6. class SampleApp : public QMainWindow, private Ui::SampleAppClass  
  7. {  
  8.    Q_OBJECT  
  9.    public:  
  10.      SampleApp(QWidget *parent = 0, Qt::WFlags flags = 0);  
  11.      ~SampleApp();  
  12.    
  13.    private:  
  14.      Ui::SampleAppClass ui;  
  15. };  
  16.    
  17. #endif // SAMPLEAPP_H  



3.       Now double-click “sampleapp.cpp” to open it in the editor

It will look like this:

3、现在双击"sampleapp.cpp”,在编辑器里打开它。

样子如下

 

[cpp]  view plain copy
  1. #include "sampleapp.h";  
  2. SampleApp::SampleApp(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)  
  3. {  
  4.    ui.setupUi(this);  
  5. }  
  6. SampleApp::~SampleApp()  
  7. {  
  8.    
  9. }  


4.       Change the constructor like shown below

4、如下修改构造函数

[cpp]  view plain copy
  1. #include "sampleapp.h";  
  2. SampleApp::SampleApp(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)  
  3. {  
  4. setupUi(this);  
  5. }  
  6. SampleApp::~SampleApp()  
  7. {  
  8.    
  9. }  


Note that the call to setupUI(this) is now lacking the “ui.” Prefix. This is importantwutransfer.com as you will get ugly exceptions when you’re mixing approaches.

注意,调用setupUI(this)函数现在缺少"ui."前缀。这点很重要wutransfer.com,因为在你混合使用多个方法以后会得到一个丑陋的例外。(ps:我依旧使用"ui."前缀)。


Adding custom Slots to your application

We are now ready to add functionality to our application. As this is a GUI application, most functions will be triggered by the user manipulating an UI element. So what we need to master here, is the way Qt handles UI events. This is where “Signals & Slots” come in.  I do recommend reading the original documentation as this topic is fundamental to understanding how Qt works. You find the docs here: Signals & Slots

To put it simple: When the user triggers an UI event, a signal is emitted. We then connect this signal to a “slot” which handles the user’s request.

This is what we want our application to do:  When the user clicks the “Do Thing A” menu item, the TextEdit widget should show the text “I did thing A!”.  Let’s see how this is done:

First, we need to define a slot which provides the functionality behind “Do Thing A”:
1.       Open “sampleapp.h” in the editor and add the following code:

添加自定义槽到你的程序

我们准备添加功能到我们的程序。因为这是一个GUI程序,使用者操作UI元素将会触发大部分功能。所以我们在这里要掌握,Qt处理UI事件的方法。这就是“信号&槽”从哪里来。我确实建议阅读原始文档,因为它是理解Qt如何工作的最基础东西。可以在这里找到文档:信号&槽

简单的说:当用户触发一个UI事件,一个信号被放出。然后我们把这个信号连接到一个“槽”,它处理用户的请求。

这是我们希望程序能做的:当用户点击"Do Thing A”菜单项,TextEdit部件会显示文本"I did thing A!”. "。让我们来看看它是如何被实现的:

首先,我们需要定义一个槽来提供"Do Thing A”背后的功能:

1、在编辑器里打开"sampleapp.h”,添加如下代码:

[cpp]  view plain copy
  1. private slots:  
  2.    void doThingA(void);  


“sampleapp.h” will now look like this:

“sampleapp.h” 将会像下面这个样子:

 

[cpp]  view plain copy
  1. #ifndef SAMPLEAPP_H  
  2. #define SAMPLEAPP_H  
  3. #include "QtGui/QMainWindow";  
  4. #include "ui_sampleapp.h";  
  5.    
  6. class SampleApp : public QMainWindow, private Ui::SampleAppClass  
  7. {  
  8.    Q_OBJECT  
  9.    
  10.    public:  
  11.      SampleApp(QWidget *parent = 0, Qt::WFlags flags = 0);  
  12.      ~SampleApp();  
  13.    
  14.    private:  
  15.      Ui::SampleAppClass ui;  
  16.    
  17. private slots:  
  18.      void doThingA(void);  
  19. };#endif // SAMPLEAPP_H  


 2.       Now open “sampleapp.cpp” in the editor and add the following code:

2、打开"sampleapp.cpp”,添加以下代码:

[cpp]  view plain copy
  1. void SampleApp::doThingA(void)  
  2. {  
  3.    textEdit->append("I did thing A!");  
  4. }  


"sampleapp.cpp” will now look like this:

"sampleapp.cpp” 现在是这个样子:

[cpp]  view plain copy
  1. #include "sampleapp.h";  
  2. SampleApp::SampleApp(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)  
  3. {  
  4.    setupUi(this);  
  5. }  
  6.    
  7. SampleApp::~SampleApp()  
  8. {  
  9.    
  10. }  
  11.    
  12. void SampleApp::doThingA(void)  
  13. {  
  14.    textEdit->append("I did thing A!");  
  15. }  


Now we need to connect the “Signal” to the “Slot” and this is done as follows:

3.       Open “sampleapp.cpp” in your editor and add the following code to the constructor (after setupUI(this):

现在我们需要把“信号”连接到“槽”,如下操作:

3、打开"sampleapp.cpp”到编辑器,并增加下列代码到构造函数(在setupUI(this):之后):

[cpp]  view plain copy
  1. QObject::connect(actionDo_Thing_A, SIGNAL(triggered()), this, SLOT(doThingA()));  


"sampleapp.cpp” will now look like this:

"sampleapp.cpp” 现在看起来是这个样子:

[cpp]  view plain copy
  1. #include "sampleapp.h";  
  2. SampleApp::SampleApp(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)  
  3. {  
  4.    setupUi(this);  
  5.    QObject::connect(actionDo_Thing_A, SIGNAL(triggered()), this, SLOT(doThingA()));  
  6. }  
  7.    
  8. SampleApp::~SampleApp()  
  9. {  
  10.    
  11. }  
  12.    
  13. void SampleApp::doThingA(void)  
  14. {  
  15.    textEdit->append("I did thing A!");  
  16. }  


Let’s examine the added line of code a bit closer:

让我们近距离检查一下增加的代码行:

[cpp]  view plain copy
  1. QObject::connect(actionDo_Thing_A, SIGNAL(triggered()), this, SLOT(doThingA()));  


With this line we connect the “triggered()” signal of the UI element “actionDo_Thing_A” (our QAction) to our custom slot called “doThingA()”.  "this” refers to the calling context (in our case the object created from this class at runtime). The “Signals & Slots” mechanism is extremely powerful and this tutorial does not do it justice, but it gets your started微笑.

We’re done! Now let’s start our application and see whether it works:

在这一行,我们把UI元素"actionDo_Thing_A” (我们的 QAction)的信号:"triggered()” 连接到我们自定义的叫做"doThingA()”的槽。"this”指的是调用上下文(在我们的例子中:运行时从这个类创建的物件(对象))。“信号&槽”机制非常强大,而本教程没有体现这一点,但是它却令我们开始了微笑

我们做完了!让我们启动程序来看看它是否工作:

 

Yes, that looks about right. That’s all folks – happy coding !

好,它看起来是正确的。伙计们,就这样结束了----快乐编程!

 

General Notes


If you change project settings, add libraries, change the UI, etc., it might happen that you get linker errors that mention “moc” or “uic”. If you get one of those, it is always worth a try to do a “clean” and rebuild the solution. These linker errors can happen in some circumstances as code is generated from your Designer file using the UIC tool (note the “UICing…” messages when building your solutions in MSVS).


Also, Qt makes strong use of meta objects, which requires a preparatory step before compiling. The MOC (Meta Object Compiler) tool is responsible for this (note the “MOCing…” messages when running a build).


Usually, all this is done behind the scenes for you. That’s the main benefit from using the Add-In!

Feedback


Please do leave a comment or PM me if you see an error - i'll fix it asap !

一般提示

如果你改变项目设置,增加库,修改UI等待,则有可能得到连接器错误,如提示"moc"或"uic“。如果发生其中任意一个错误,尝试做一个"清理"并重建解决方案总是值得的。

这些连接器错误能在某些环境发生,因为代码是使用UIC工具从你的设计师文件生成的(在msvs中编译你的解决方案时,注意"UICing.."消息)。

同样,Qt大量使用元物件,而后者在编译以前需要一个预先准备的步骤。MOC(元物件编译器)工具负责这个事情(在运行一个编译时,注意"MOCing..."信息)。

通常,所有的这些都是在幕后为你做好。这也是使用插件(Add-In)的主要好处。

 

反馈

如果你看到一个错误,请留下评论或者给我发信息------我会尽快修正它。

 

(致谢 sxzhongji和meneye)

于善鹏 2013.04.07 08:00 am ~ 02:40 pm


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值