问题
i have a simple window with a quit button in qt.The working code is shown below
#include <QApplication>
#include <QDialog>
#include <QPushButton>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
};
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
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()));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget widget;
widget.show();
return app.exec();
}
Now i want to code this program using qt designer.I created a widget named "mywindow" and a button inside that main widget named "btquit" in the ui file using qt designer. How to rewrite the above code with the ui file.The name of ui file is mywindow.ui
回答1:
#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();
}
回答2:
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;
}
来源:https://stackoverflow.com/questions/9696317/how-to-use-ui-file-for-making-a-simple-widget