Qt初识,快速上手

前备工作

创建一个有关QWidget的项目

Qt Hello World 程序

QLabel显示文本

1.代码呈现文本

Widget.cpp
cpp 复制代码
#include "widget.h"
#include "ui_widget.h"
#include<QLabel>  //别忘了包头文件
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //注意:我们需要this作为对象树的父节点,所以代码写在Widget类里面
    QLabel* mylabel = new QLabel(this);
    mylabel->setText("Hello World");

}

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

默认生成在左上角

widget.ui

点击widget.ui会跳到如下窗口,我们找到 Label并拖动到右边空白区域。

通过对象查找器定位到2.1 2.2

可以点击白色背景下2.1的HelloWorld修改也可以在2.2中text的右边栏修改

QpushButton显示按钮

代码类似

widget.cpp
cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

//#include<QLabel>
#include<QPushButton>

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


    // QLabel* mylabel = new QLabel(this);
    // mylabel->setText("Hello World");

    QPushButton* mypushButton = new QPushButton(this);
    mypushButton->setText("Hello World!!!");


}

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

PushButton顾名思义就是设置一个按钮

widget.ui

从1拖入ui面,在2中可以修改按钮名

这个命名和connect的使用有关。

connect控制按钮变换

widget.h

只添加这一行声明

widget.cpp
cpp 复制代码
#include "widget.h"
#include "ui_widget.h"
//#include<QLabel>
#include<QPushButton>
#include<QString>
#include<QObject>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);


    // QLabel* mylabel = new QLabel(this);
    // mylabel->setText("Hello World");

    // QPushButton* mypushButton = new QPushButton(this);
    // mypushButton->setText("Hello World!!!");


    //ui界面创建按钮使用
    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::handleClick);

    // 也可以代码生成按钮。
    // QPushButton* mypushButton = new QPushButton(this);
    // connect(mypushButton , &QPushButton::clicked, this, &Widget::handleClick);
    
}

//ui,pushButton等等是QWidget内的,Widget继承了QWidget,故可以直接使用。
void Widget::handleClick()
{
    if(ui->pushButton->text() == QString("hello world"))
    {
        ui->pushButton->setText("hello Qt");
    }
    else
    {
        ui->pushButton->setText("hello world");
    }
}


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

现在按钮可以点击变换了。

相关推荐
Cloud_Shy61819 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第三章 Item 21 - 24)
开发语言·人工智能·笔记·python·迭代器模式
多彩电脑23 分钟前
Lua中的元表里的__index和__newindex
开发语言·lua
野生技术架构师31 分钟前
2026 Java面试宝典(春招/社招/秋招通用):没有前言,只有答案,直接开背
java·开发语言·面试
nnnnichijou37 分钟前
Qt 6.9 嵌入式 Linux 交叉编译全栈填坑指南(以树莓派5 AArch64 为例
qt·嵌入式·交叉编译·qml·树莓派5
人道领域1 小时前
【LeetCode刷题日记】131.分割回文串,动态规划优化
java·开发语言·leetcode
z落落1 小时前
C# 接口 interface (多接口实现、类+接口、成员重名)
java·开发语言
864记忆2 小时前
OD车牌号获取流程
qt
知识的宝藏3 小时前
Xpaht self::div 轴语法
开发语言
keykey6.3 小时前
卷积神经网络(CNN):让AI学会“看“
开发语言·人工智能·深度学习·机器学习
IsJunJianXin3 小时前
谷歌搜索cookie NID逆向生成
开发语言·python·google搜索·sgss·nid-cookie·算法生成nid·google-cookie