Display a form in Qt

2019-07-20 19:59发布

This should be very easy.
I'm using Qt Creator and I have made a Qt Gui Application (That had main.h, main.ui and main.cpp)

I just created a Qt Designer Form Class that also has a header file, ui, and a class. I have made an action inside my main.cpp called ShowSecondForm:

void Main::ShowSecondForm()
{

}

Everytime I execute ShowSecondForm(); I want the second form to be displayed.
What do I put inside so my form will open?
Also, is is possible to pass a string to the form while opening it? Like ShowSecondForm(const QString&)?

Some notes that may help you:

  • I would like to have 2 forms opened at the same time.
  • It will also be a class as it will compute different things.

标签: qt qt4
2条回答
做自己的国王
2楼-- · 2019-07-20 20:31

If you're opening one form from another, you might want to do something like this:

m_form = new MyForm (this);
m_form->show();

Here you first create the form object, and then show it. Note this is passed as a parent - when a parent form is destroyed, children will be closed and destroyed automatically. That also means you don't need to bother cleaning up in destructor. If you need to open several forms, you will need an object for each of them.

m_form1 = new MyForm (this);
m_form1->show();
m_form2 = new MyForm (this);
m_form2->show();

Finally, there are many ways to pass a string to the form. It's your form, so you may want to modify it's constructor, so that it would accept string upon creation, like m_form = new MyForm ("Some string", this); Or you may want to add a property to your form. Sometimes, you may also want to use QObject's built-in property system, take a look at QObject::setProperty() and QObject::property() functions.

查看更多
三岁会撩人
3楼-- · 2019-07-20 20:42

I suspect this tutorial might be helpful. Presumably you have a main.ui, a main.h and a main.cpp.

Run the uic program over your main.ui file, to generate your ui_main.h header (if you're not using qmake), but otherwise the basic setup is in that tutorial.

查看更多
登录 后发表回答