QT学习笔记—widget窗口应用程序

QT Creator默认有三种创建窗口类选择:

QWidget
QMainWidow
QDialog

三种窗口类的关系:

在这里插入图片描述

QMainWidownQDialog继承自QWidget。QWidget是最简单的窗口,什么都没有。

创建一个widget窗口

工程文件:

工程文件在不熟悉情况下不要随意改动

#-------------------------------------------------
#
# Project created by QtCreator 2020-08-02T13:46:48
#
#-------------------------------------------------

QT       += core gui  #QT包含的模块

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets #大于4.0版本以上包含widget模块

TARGET = MyWidget    #生成应用程序的名字
TEMPLATE = app     #模板,应用程序模板 app——application

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

#源文件
SOURCES += \
        main.cpp \
        mywidget.cpp
#头文件
HEADERS += \
        mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>

class myWidget : public QWidget //继承QWidget
{
    Q_OBJECT                    //Q_OBJECT宏,允许类使用信号和槽的机制

public:
    myWidget(QWidget *parent = 0); //构造函数
    ~myWidget();                   //析构函数
};

#endif // MYWIDGET_H
#include "mywidget.h"
#include <QPushButton>

myWidget::myWidget(QWidget *parent)
    : QWidget(parent)    //初始化列表
{
	setWindowTitle("widget窗口");   //设置窗口标题
	
    this->setFixedSize(600, 400);  //设置窗口固定大小

    QPushButton *btn = new QPushButton;  //创建一个button
    btn->move(100, 200);
    btn->setText(tr("第一个按钮"));
    btn->setParent(this);    //设置button的父类
    btn->show();           //将button显示出来
}

myWidget::~myWidget()
{

}

在这里插入图片描述

#include "mywidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    //a是QT应用程序对象,有且仅有一个
    QApplication a(argc, argv);

    //窗口对象, 父类是QWidget
    myWidget w;
    w.show();  //窗口默认不会显示,调用窗口对象的方法,显示窗口

    return a.exec(); //让应用程序对象进入消息循环处理机制
}

猜你喜欢

转载自blog.csdn.net/qq_36413982/article/details/107744444