Qt 入门第二篇:Qt Creator 手敲代码实现简单窗口

27 阅读2分钟

前情提要

        上篇写了Qt的作用、安装、编辑器、原理、信号与槽。这一篇记录利用Qt Creater 手搓代码的方式创建一个简单的命令窗口。

对象分析

分析一下这张图片的布局:

文字                                                                 叉号

图片                                 标签

标签   行编辑框

                           按钮   按钮   按钮

布局大概就是这样

把第二行的图片及文字舍去,只剩下六个控件,就要写六个对象

代码编写

(1)框架

先写一个固定格式,解释在图下。

#include "widget.h"

#include <QApplication>

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

头文件QApplication是Qt必须要用的头文件;widget.h是自定义的头文件;在这里与标准C++的区别就是main()括号里需要传参数:int argc, char *argv[ ];还有QApplication一定要声明一个对象并把传入的参数传进构造函数里;return也不能直接返回0,需要返回这个对象的exec,这样可以实现在用户没有关闭之前一直是无限循环的

(2)具体对象

对象声明

#include <QApplication>
#include<QLabel>
#include<QLineEdit>
#include<QPushButton>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLabel *InfoLabel = new QLabel;                         //这一对象是置于左上角的标题标签
    QLabel *openLabel = new QLabel;                         //这一对象是提示打开的标签
    QLineEdit *cmdLineEdit = new QLineEdit;                 //这一对象是行编辑框
    QPushButton *commitButton = new QPushButton;            //这一对象是确认按钮
    QPushButton *cancelButton = new QPushButton;            //这一对象是取消按钮
    QPushButton *browseButton = new QPushButton;            //这一对象是浏览按钮    
    return app.exec();
}

先声明六个需要的对象

给对象附文本

    InfoLabel->setText("运行");
    openLabel->setText("打开(O):");
    commitButton->setText("确认");
    cancelButton->setText("取消");
    browseButton->setText("浏览");

利用类成员函数setText为对象附文本

确定布局

#include<QHBoxLayout>
#include<QVBoxLayout>

第一个是水平布局头文件,第二个是垂直布局头文件

    QHBoxLayout *cmdLayout = new QHBoxLayout;               //第一层水平布局对象
    cmdLayout->addWidget(openLabel);
    cmdLayout->addWidget(cmdLineEdit);
    QHBoxLayout *buttonLayout = new QHBoxLayout;            //第二层水平布局对象
    buttonLayout->addWidget(commitButton);
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addWidget(browseButton);
    QVBoxLayout *mainLayout = new QVBoxLayout;              //总的垂直布局对象
    mainLayout->addWidget(InfoLabel);
    mainLayout->addLayout(cmdLayout);
    mainLayout->addLayout(buttonLayout);

可以看出addWidget这个函数是添加控件,addLayout这个函数是添加布局,括号里的参数就是要添加的内容

构造窗口

#include<QWidget>

包含这个头文件

    QWidget w;
    w.setLayout(mainLayout);
    w.show();

声明一个窗口对象,再用对象的成员函数添加布局和展示

效果展示

                               

如图,左上角展示的是项目名称,该出现在那里的运行出现在了下边。

总结

        窗口的标题是工程标题,声明的对象都是窗口的内容。

        对象包括布局对象、标签对象、按钮对象、输入框对象

        这个项目并没有涉及到信号和槽