QT学习从入门到入门 step by step (3)

接上文

通过上边的两种方法,大体了解了Qt的类及界面设计器的用法,下边的方法是把Qt的界面封装成一个自定义类

3. 通过自定义类生成helloworld

(1)还是建立一个空项目

(2)添加一个自定义界面

(3)建一个c++类,继承自 QDialog,通过此可学习QDialog类的继承方法,上代码

//.h文件 -> testDialog.h

#ifndef TEST4CLASS_H  
#define TEST4CLASS_H  

#include <QDialog>       //对QDialog的include
namespace Ui//前置声明    // 对前面生成的Ui界面的前置声明
{
class testDialog;
}
class testDialog : public QDialog //自定义类 继承自 QDialog
{
    Q_OBJECT   //Qt的宏,介绍说是扩展的普通C++类,具体作用以后再学习

public:
    explicit testDialog(QWidget *parent = 0); //构造函数
    ~testDialog(); //析构函数
private:
    Ui::testDialog *ui; //该自定义类定义了一个Ui命名空间的同名类的成员ui
};
#endif // TEST4CLASS_H
//.cpp文件 -> testDialog.cpp

#include "testDialog.h"
#include "ui_testdialog.h"

testDialog::testDialog(QWidget *parent): QDialog(parent), ui(new Ui::testDialog) //初始化类成员列表时,创建ui的实体
{
    ui->setupUi(this);//用 setupUi函数绑定设置的界面到此类
}
testDialog::~testDialog()
{
    delete ui;
}

(4)main函数

#include "QApplication"
#include "testDialog.h"
int main(int argc, char*argv[])
{
    QApplication a(argc, argv);
    testDialog w;
    w.show();
    int ret = a.exec();
    return ret;
}

4. 使用Qt设计师界面类 生成helloworld

 (1)建空项目

(2)ctrl+N 选择 Qt -> Qt设计界面类, 输入类名,一路默认确定后, qt自动完成类的创建及界面的创建

(3)建立main函数,同上

至此, helloworld 的生成方法学习完毕。 通过上述4步,一步步的完成学习, 了解了Qt设计师界面类帮我们自动完成了哪些操作,并且可以更深刻的了解由qt自动生成的这些代码的实际用途。

猜你喜欢

转载自blog.csdn.net/sierllen/article/details/82773019