how to use ui file for making a simple widget?

谁都会走 提交于 2019-12-05 08:08:35
#include <QApplication>
#include <QDialog>
#include <QPushButton>
#include "ui_mywindow1.h"

class MyWidget : public QWidget,private Ui::mywindow
{
public:
    MyWidget(QWidget *parent = 0);
};

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    setupUi(this);


    connect(btquit, SIGNAL(clicked()), qApp, SLOT(quit()));
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

I prefer to have the ui as private member in the widget's class. I assume that in the designer you have named the widget as mywindow (the objectName from the properties).

// MyWindow.h

#include <QWidget>

// Forward declaration of your ui widget
namespace Ui {
    class mywindow;
}

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

private:
    // private pointer to your ui
    Ui::mywidget *ui;
};

And then in your .cpp you have to do the following:

#include "mywindow.h"
//1. Include the auto generated h file from uic
#include "ui_mywindow.h"
#include <QPushButton>

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent), 
      //2. initialize the ui
      ui(new Ui::mywindow)
{
    //3. Setup the ui
    ui->setupUi(this); 

    // your code follows
    setFixedSize(200, 120);

    QPushButton *btquit = new QPushButton(tr("Quit"), this);
    btquit->setGeometry(62, 40, 75, 30);
    btquit->setFont(QFont("Times", 18, QFont::Bold));

    connect(btquit, SIGNAL(clicked()), qApp, SLOT(quit()));
}

MyWidget::~Mywidget()
{
    delete ui;
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!