• 博客主页:Duck Bro 博客主页
  • 系列专栏:Qt 专栏
  • 关注博主,后期持续更新系列文章
  • 如果有错误感谢请大家批评指出,及时修改
  • 感谢大家点赞👍收藏⭐评论✍

使用两种方式实现helloworld

文章编号:Qt 学习笔记 / 05


文章目录

  • 使用两种方式实现helloworld
  • 一、实现hello world的两种方式
  • 二、图形化实现hello world
  • 1. 实现步骤
  • 2. 代码解析
  • 三、纯代码实现hello world
  • 1. 代码实现
  • 2. 输出结果



一、实现hello world的两种方式

【Qt 学习笔记】使用两种方式实现helloworld_qt


两种方式,在界面上是实现hello world

  • 通过图形化拖拽控件的方式实现hello world
  • 通过在widget.cpp文件中进行编码实现hello world

二、图形化实现hello world

1. 实现步骤

  1. 先创建一个Qt项目
    步骤参考:使用QtCreator创建及运行项目
  2. 点击widget.ui 文件,弹出以下界面
  3. 【Qt 学习笔记】使用两种方式实现helloworld_学习_02

  4. 在左侧 Display Widgets 找到Label标签,拖拽至界面上
  5. 【Qt 学习笔记】使用两种方式实现helloworld_qt_03

  6. 修改Label标签上的文字,修改成helloworld
  7. 【Qt 学习笔记】使用两种方式实现helloworld_学习_04

  8. 点击运行,如下图所示
  9. 【Qt 学习笔记】使用两种方式实现helloworld_笔记_05

2. 代码解析

刚才往界面上拖拽的QLabel控件,此时,ui文件的xml就会多出这一段代码

<widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>300</x>
     <y>240</y>
     <width>121</width>
     <height>51</height>
    </rect>
   </property>
   <property name="text">
    <string>hello world</string>
   </property>
  </widget>

进一步qmake就会在编译的时候,基于这一段内容生成一段C++代码,来构建出界面内容。


三、纯代码实现hello world

1. 代码实现

#include "widget.h"
#include "ui_widget.h"
#include <QLabel>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //更推荐这种在堆上创建
    QLabel* label =new QLabel(this);   // 需要包含头文件<QLabel>
    //QLabel label;					   //这个也可以
    label->setText("hello world");     //设置控件中显示的文本

}

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

2. 输出结果

代码实现的hello world 默认是在左上角,如果想在其他位置,后续文章进行介绍

【Qt 学习笔记】使用两种方式实现helloworld_笔记_06