开发者

Displaying a second form in Qt

开发者 https://www.devze.com 2023-02-08 19:35 出处:网络
I know this question has been asked a few time, (http://stackoverflow.com/questions/4436511/display-a-form-in-qt)

I know this question has been asked a few time, (http://stackoverflow.com/questions/4436511/display-a-form-in-qt)

I am trying to open an existing form in my Qt C++ project. it needs to be a subform instead of QDialog box.

both forms have a .ui, .h and .cpp file with them.

in my mwindowtest.cpp I have

//this is used to handle the button click to open the new form
connect(btnConnect, SIGNAL(click()), this, SLOT(openNewWi开发者_Go百科ndow()));

for function is:

void mWindowTest::openNewWindow(){

   mForm = new dialog (this);
   mForm->show();

}

in my mwindowtest.cpp I have:

#include <dialog.h>  //second form
class dialog;

I'm now getting the error mForm was not declared in this scope. but I am not sure what to declare mForm as in my Header file.

any tips would be greatly appreciated.

Thanks


In your mywindowtest.hpp you have to declare the pointer first:

// mytestwindow.hpp
// ...
private:
    dialog* mForm;
// ...

// mytestwindow.cpp
void mWindowTest::openNewWindow()
{
    mForm = new dialog (this);
    form->show();
}

Or you declare it directly in your cpp, but then it is no member and only known in openNewWindow().

void mWindowTest::openNewWindow()
{
    dialog* form = new dialog (this);
    form->show();
}

When you work with Qt you should know the basics of C++. This example is one of those basics. Use Google and read some stuff about pointer tutorials and dynamic memory allocation.

Hope that helps. :)


In your example you will have memory leak since each time button btnConnect is clicked you will reallocate memory for your form, without deleting the previous first.

Concerning your problem, we need to know how is declare dialog in dialog.h to be able to really help you. In your mywindowtest.cpp you have included the file and redefined the class. Try to put

class dialog

in your hpp file and

#include <dialog.h>

in your cpp file.

Hope that helps

Edit:

In your slot:

delete mForm;
mForm = new dialog();
dialog->show();

It's the minimum to avoid memory leaks; And don't forget to delete mForm in MyWindowTest destructor too if not null;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号