VS2010中的Qt - 无法使用设计器创建的对象

Qt in VS2010 - Can't use the Objects create by the Designer

本文关键字:创建 对象 Qt 中的 VS2010      更新时间:2023-10-16

我在Visual Studio 2010中使用Qt,但我有疑问。每当我使用Qt设计器创建GUI时,在Visual中编译时,我无法访问设计器自动创建的对象,如按钮、列表框等。。。我应该怎么做才能使用它们?

我的观点是,我不能创建事件、插槽、信号等,因为这些对象似乎不存在于我的main.cpp和mainclass.cpp中。

谢谢大家!

我使用的是带有QT 4.8.0的VS 2010。

#include <QListWidget.h>
#include <stdio.h>
#include <string.h>
#include "ui_ratagbc.h"
class dasm: QObject
{
    Q_OBJECT
public:
    dasm(void);
    ~dasm(void);
    int DAsm(FILE *,int);
private:
    Ui::RataGBCClass *ui;
};

要在代码中访问GUI,请包含运行uic工具的结果。创建一个类,并将uic生成的类的实例作为成员变量,该实例位于Ui命名空间中。

#include "ui_MyGUI.h" //automatically generated by uic tool
class MyClass : public QDialog //or whatever type of GUI you made
    {
    Q_OBJECT //this macro flags your class for the moc tool
    //other variables and functions
    Ui::MyGUI ui;
    };

您可以通过此"ui"对象访问:ui.label->setText("New label text set in source file");

在构造函数中,调用ui.setupUi(this)

请注意Q_OBJECT宏-如果您正在定义信号和插槽或类似的东西,您需要Q_OBJECT在那里标记类,以便moc工具识别它。

编辑以回答评论中的后续问题:听起来你想做的就是使用信号/插槽系统。在您的类定义中,包括以下内容:

class MyClass
{
//other stuff
public slots:
void customSlot(){/* your actions here */}
//other stuff
};

然后在其他地方,通常在构造函数或初始化函数中,包括以下行:

connect(ui.button, SIGNAL(clicked()), this, SLOT(customSlot()));

moc工具处理大部分设置。单击该按钮后,您的自定义插槽将被触发。