0

My friend and I have each created parts of a GUI using Qt 4. They both work independently and I am trying to integrate his form with the my main window. As of now this is the code I am using to try and load his form:

//connect buttons and such
connect(exitbtn, SIGNAL(triggered()),this,SLOT(terminated()));
connect(add, SIGNAL(triggered()),this,SLOT(add_rec()));

void MainWindowImpl::add_rec()
{
  //form quits as soon as it loads...?
  DialogImpl dia;//name of his form
  dia.show();
}

I have included his header file. The program compiles but when I hit the trigger his form loads up for maybe half a second and then closes. Does anyone know what I am doing wrong?

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
  • 1
    What happens to dia at the end of add_rec? When are local variables cleaned up? – Bill Nov 11 '09 at 18:58
  • To expand on [this answer](http://stackoverflow.com/a/1705583/594137), it's your familiarity with C++ rather than Qt that's thrown you here. I'd suggest getting a [good book](http://stackoverflow.com/q/388242/594137) which covers the basics of C++ for times such as this. – Samuel Harmer Jan 30 '12 at 13:30

3 Answers3

2

You have almost get it right. This is because the RAII of C++. If you allocate the Dialog on stack, it would be destructed as soon as the function return.

J-16 SDiZ
  • 26,473
  • 4
  • 65
  • 84
2

Assuming MainWindowImpl inherits publically from QWidget, you're looking for this:

void MainWindowImpl::add_rec() 
{
  // passing "this" to the constructor makes sure dialog will be cleaned up.
  // Note that DialogImpl will need a constructor that takes a
  // QObject* parent parameter.
  DialogImpl* dialog = new DialogImpl(this);

  dialog->show(); 
}

Look at the Qt documentation for examples of how the constructors should look.

Bill
  • 14,257
  • 4
  • 43
  • 55
-2

Apparently QT4 only allows one instance of an object at a time, however pointers are another matter. Change both the main.cpp and what ever your main window to look something like this:

DialogImpl *dia=new DialogImpl;
dia->show();
Caleb Huitt - cjhuitt
  • 14,785
  • 3
  • 42
  • 49
  • 1
    This is wrong. The problem is that dia is getting destructed at the end of the function. (Qt4 definitely allows you to have multiple instances of a class at a time.) – Bill Nov 11 '09 at 18:57