简体   繁体   中英

how to use objects of the widgets in QT

In my application I'm having 2 widgets named as widget and form . But if i try to create a pointer object of widget widget in widget form header file , it is giving the error like "Form does not name a type". Refer my used code below:

main.cpp

#include <QtGui/QApplication>
#include "widget.h"
#include "form.h"
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  Widget *w = new Widget();
   w->show();
  return a.exec();
 }

widget.cpp

#include "widget.h"
Widget::Widget(QWidget *parent) :QWidget(parent)
{
  setupUi(this);
}

widget.h

 #ifndef WIDGET_H
 #define WIDGET_H

 #include "ui_widget.h"
 #include "form.h"
 class Widget : public QWidget, private Ui::Widget
 {
    Q_OBJECT
    public:
        explicit Widget(QWidget *parent = 0);
        Form *f ;//i try to create pointer object for Form
 };
 #endif // WIDGET_H

form.cpp

 #include "form.h"
 #include "widget.h"

 Form::Form(QWidget *parent) :QWidget(parent)
 {
   setupUi(this);
 }

form.h

#ifndef FORM_H
#define FORM_H

#include "ui_form.h"
#include "widget.h"
class Form : public QWidget, private Ui::Form
{
  Q_OBJECT
  public:
       explicit Form(QWidget *parent = 0);
};

What I'm doing wrong?

You should put a forward declaration of class Form in widget.h instead of #include ing form.h. The problem is that you include form.h, which includes widget.h, which tries to include form.h, but can't because of the include guard. Therefore, in widget.h, class Form is undefined, although it looks to the user to be defined.

The problem is that widget.h includes form.h , which includes widget.h . The header guards ( #ifndef ) cause the second include to be skipped.

For declaring a pointer variable in a header a forward declaration will suffice:

SomeClass.h

 class Form; // forward declaration

 class SomeClass {
 public:
    SomeClass();
    // ...
 private:
    Form* form; // pointer to Form
 };

SomeClass.cpp

SomeClass::SomeClass() 
{
     form = new Form();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM