c++ - qt4 designer 添加自定义类

标签 c++ qt4 qt4.8

您好,我在 qt4 设计器中制作了一个图形用户界面,想添加带有自定义类的自定义插槽。 它的项目可以很好地编译而没有错误,但是我的自定义函数无法正常工作我做错了什么?我将向您展示 qt4 设计器为我制作的头文件,并向您展示我的自定义文件以及 main.cpp.. 首先是 main.cpp

我已经修改了我的代码,这是我现在所拥有的我已经添加了一个名为 sweetest.cpp 的文件并编辑了 sweetest.h 这是我的新文件和我收到的错误..

第一个main.cpp

#include "ui_sweetguiform.h"

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     QWidget *widget = new QWidget;
     Ui::SweetGuiForm ui;
     ui.setupUi(widget);

     widget->show();
     return app.exec();
 }

现在是我的自定义头文件 sweetest.cpp

#include "sweetest.h"
// trying to include the .moc file wouldnt work at all.

现在是带有我的代码的 sweettest.h 文件

#include "ui_sweetguiform.h"

class SweetGuiForm : public QWidget
{
    Q_OBJECT
public:
    SweetGuiForm( ): ui( new Ui::SweetGuiForm )
    {
        ui->setupUi( this );
    connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(on_buttonBox_accepted()));
    }

public slots:
    void on_buttonBox_accepted()
    {
         ui.textEdit->setText(QString::number(23));

    }

protected:
    Ui::SweetGuiForm* ui;
};

这是我收到的编译错误..我真的卡住了

In file included from sweetest.cpp:1:
sweetest.h: In member function ‘void SweetGuiForm::on_buttonBox_accepted()’:
sweetest.h:16: error: request for member ‘textEdit’ in ‘((SweetGuiForm*)this)->SweetGuiForm::ui’, which is of non-class type ‘Ui::SweetGuiForm*’
make: *** [sweetest.o] Error 1

我觉得我越来越近了

最佳答案

信号和槽的工作方式是您必须将信号连接到槽。在您的代码中,最简单的方法是在 SweetGuiForm 的构造函数中。您需要添加:

SweetGuiForm() : ui(new Ui::SweetGuiForm) {
  ui->setupUi(this);
  connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(on_buttonBox_accepted()));
}

当 buttonBox 发出它的接受信号时,所有连接到它的槽都将被调用。

更新 1

在进一步检查您的代码时,您还缺少 Qt MOC(元对象编译器)系统(http://qt-project.org/doc/qt-4.8/moc.html)使用的 Qt 宏:

class SweetGuiForm : public QWidget
{
  Q_OBJECT
  public:
  ...
};

您还必须通过 MOC 工具推送代码。它将生成一个需要包含在您的源代码中的源文件。我记得,您必须将其包含在 cpp 文件中;包含在标题中是有问题的。以下应该足够了:

sweetguiform.cpp:

#include "suiteguiform.h"
#include "sweetguiform.moc"

更新 2

进一步思考,当您使用特殊名称(例如 on_buttonBox_accepted)命名插槽时,我忘记了自动信号/插槽连接功能。这里有一篇博客文章:http://qtway.blogspot.com/2010/08/automatic-connections-using-qt-signals.html .我自己没有使用过它,所以我不能评论它在使用 ui 成员变量时的工作能力,尽管我怀疑它在那种安排下不起作用。无论如何,您仍然需要 Q_OBJECT 宏和 MOC。

关于c++ - qt4 designer 添加自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20763148/

相关文章:

python - 加载了错误的 Mac OS X 框架

c++ - 使用英特尔编译器构建 Qt 4 = Unresolved 错误

c++ - QString 中的哪个函数对用于转换为 std::string 或从 std::string 转换?

c++ - 全局声明 QStringlist 变量,使用 QFileDialog 获取位置路径并将其打印到 lineEdit 并在 QProcess 中使用它

c++ - 如何减少 OpenMP 中 for 循环内关键部分内的值?

c++ - 重写函数的默认参数

c++ - 从 Local<String> 计算一行中的 UTF8 字符

c++ - 数组越界元素的值——它应该在每次执行时改变还是保持不变?

macos - Qt 4.8 - 在 mac-mini (OS X Lion) 上检测 SD 卡的插入和移除