Qt - 没有课程的显示设计师表格

Mik*_*ika 1 forms qt designer

在Qt中,我创建了一个没有类的Designer表单.所以基本上,我只有一个文件myform.ui.我应该写什么代码来显示表单?

lee*_*mes 6

如果在该FORMS部分的.pro中包含(d)ui文件,则在构建过程中将生成一个特殊的头文件.包含此头文件并使用它将子窗口小部件添加到运行时期间所需的任何QWidget.

此示例中的ui文件名为mywidget.ui.在.pro文件中,有一行说

FORMS += mywidget.ui
Run Code Online (Sandbox Code Playgroud)

QtCreator将在项目资源管理器中显示该文件.此步骤很重要,否则在构建项目时不会生成头文件!

然后将生成的头文件称为ui_mywidget.h,并调用组成设计窗口的类Ui::MyWidget,可以按如下方式使用.

解决方案1(QtCreator在您创建新的" Qt Designer表单类 " 时建议的方式):

namespace Ui {
class MyWidget;
}

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();

private:
    Ui::MyWidget *ui;     // Pointer to the UI class where the child widgets are
};
Run Code Online (Sandbox Code Playgroud)

#include "ui_mywidget.h"
MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);    // Create and add the child widgets to this widget
}

MyWidget::~MyWidget()
{
    delete ui;
}
Run Code Online (Sandbox Code Playgroud)

然后,这个小部件就可以使用了,它将包含您在实例化时在设计器中创建的子小部件:

MyWidget widget;
widget.show();
Run Code Online (Sandbox Code Playgroud)

解决方案2(不继承自QWidget):

#include "ui_mywidget.h"
...
QWidget *widget = new QWidget(...);
Ui::MyWidget ui;         // Instance of the UI class where the child widgets are
ui.setupUi(widget);      // Create and add the child widgets to this widget
widget->show();
...
Run Code Online (Sandbox Code Playgroud)