【Qt 学习笔记】Day3 | 使用两种方式实现helloworld


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

Day3 | 使用两种方式实现helloworld

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

文章目录

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

一、实现hello world的两种方式

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

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

二、图形化实现hello world

1. 实现步骤

  1. 先创建一个Qt项目

    步骤参考:使用QtCreator创建及运行项目

  2. 点击widget.ui 文件,弹出以下界面

  3. 在左侧 Display Widgets 找到Label标签,拖拽至界面上

  4. 修改Label标签上的文字,修改成helloworld

  5. 点击运行,如下图所示

2. 代码解析

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

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. 代码实现

cpp 复制代码
#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 默认是在左上角,如果想在其他位置,后续文章进行介绍


相关推荐
头发还没掉光光11 小时前
Linux网络之IP协议
linux·运维·网络·c++·tcp/ip
狐5712 小时前
2026-01-22-LeetCode刷题笔记-3507-移除最小数对使数组有序I
笔记·leetcode
2501_9444241212 小时前
Flutter for OpenHarmony游戏集合App实战之连连看路径连线
android·开发语言·前端·javascript·flutter·游戏·php
C系语言12 小时前
python用pip生成requirements.txt
开发语言·python·pip
燃于AC之乐12 小时前
深入解剖STL Vector:从底层原理到核心接口的灵活运用
开发语言·c++·迭代器·stl·vector·源码分析·底层原理
wrj的博客19 小时前
python环境安装
python·学习·环境配置
优雅的潮叭19 小时前
c++ 学习笔记之 chrono库
c++·笔记·学习
星火开发设计19 小时前
C++ 数组:一维数组的定义、遍历与常见操作
java·开发语言·数据结构·c++·学习·数组·知识
月挽清风20 小时前
代码随想录第七天:
数据结构·c++·算法
TTGGGFF20 小时前
控制系统建模仿真(一):掌握控制系统设计的 MAD 流程与 MATLAB 基础运算
开发语言·matlab