Qt学习笔记4——窗口和控件

1.1 窗口定义

窗口:当一个部件没有嵌入到其他部件中,则把这个部件叫作窗口或者顶层窗口,顶层窗口是没有父窗口的,一般的,这些窗口都会被列在任务栏中。通常,一个窗口会包含有标题栏,窗口边框等。如果一个窗口具有父类,则这个窗口被称为是次级窗口,例如设置了父类的QDialog就是次级窗口,而这些窗口不会被列在任务栏中,而是在各自的父窗口之上。

控件:当一个窗口嵌入到其它窗口中,则它本身的标题栏会隐藏,那这些窗口就叫作控件,也可以叫作非顶层窗口或子窗口。

父窗口,子窗口:当部件1嵌入到部件2中,就把部件2称作是部件1的父窗口,而部件1是部件2的子窗口。

下图,MyFirstWidget是窗口,TextLabel,ComboBox,PushButton,LineEdit,CheckBox等都是控件,并且它们的父窗口是MyFirstWidget。
这里写图片描述

在Qt中主要有三种顶层窗口:

QWidget:最基础的窗口,所有窗口及控件都继承QWidget。

QDialog:对话框窗口,可类比Windows中的对话框。

QMainWindow:主窗口,一般主窗口会包括标题栏,菜单栏,工具栏, 中心部件,停靠窗口,状态栏等。可类比桌面应用程序。

1.2 验证父子窗口
学习就是不知疲倦的写代码,写的多了,意思就明白了

代码如下:
新建项目ParentChildWidget,类名ParentChildWidget,基类选择QWidget。

在main.cpp包含QPushButton,输入如下代码

#include "parentchildwidget.h"
#include <QApplication>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ParentChildWidget w;
    w.show();

    QPushButton buttonWindow;
    buttonWindow.setText("我是窗口");
    buttonWindow.show();
    buttonWindow.resize(200, 100);

    return a.exec();
}

在parentchildwidget.cpp中,包含QPushButton,在构造函数中添加如下代码

#include <QPushButton>
#include "parentchildwidget.h"
#include "ui_parentchildwidget.h"

ParentChildWidget::ParentChildWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParentChildWidget)
{
    ui->setupUi(this);

    QPushButton* buttonChild = new QPushButton(this);
    buttonChild->setText("我是控件");
}

ParentChildWidget::~ParentChildWidget()
{
    delete ui;
}

运行程序,注意文件以utf-8编码保存,否则显示乱码。

结果会看到有两个窗口同时运行,一个button成为顶层窗口,另一个button因为设置了父窗口,所以成为控件,同时标题栏被隐藏。

这里写图片描述

1.3 父子窗口特性

现在修改main函数

#include "parentchildwidget.h"
#include <QApplication>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ParentChildWidget w;
    w.show();

//    QPushButton buttonWindow;
//    buttonWindow.setText("我是窗口");
//    buttonWindow.show();
//    buttonWindow.resize(200, 100);

    return a.exec();
}

修改parentchildwidget.cpp构造函数

ParentChildWidget::ParentChildWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParentChildWidget)
{
    ui->setupUi(this);

    for (int i = 1; i <= 3; ++i)
    {
        QPushButton* buttonChild = new QPushButton(this);
        buttonChild->setText(QString("我是控件%1").arg(i));
        buttonChild->resize(100*i, 100);
        connect(buttonChild, SIGNAL(clicked()), buttonChild, SLOT(close()));
    }
}

这里写图片描述

我们看到窗口中只有一个按钮(我是控件3),点击按钮,出现我是控件2,再点击出现我是控件1,并且所有的按钮都在窗口的左上角。

其实,控件1和控件2都被控件3遮盖住了。从这个例子中,可以得出以下结论:

1.子窗口的坐标系是以父窗口的坐标系为基准的,并且默认情况下定位在父窗口的(0,0)点处,窗口的(0,0)点都是在窗口绘图区域的左上角。水平方向向右为正,垂直方向向下为正。可以调用move()函数让控件重新定位,如果传递给它负值,其左上角会移出父窗口的可见区域,则该控件也只绘制可见部分的区域。

2.后创建的控件会覆盖在先创建的控件上。

--------------------- 本文来自 _毛哥 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/mao_hui_fei/article/details/79595759?utm_source=copy

猜你喜欢

转载自blog.csdn.net/IAlexanderI/article/details/82940830