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;
}

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

相关推荐
少司府7 小时前
C++进阶:智能指针
开发语言·数据结构·c++·b树·算法·c·智能指针
matlab代码7 小时前
基于matlab的红绿灯图像检测识别系统【源码60期】
开发语言·matlab
博界IT精灵7 小时前
C语言中的数据类型及其转换
c语言·开发语言
软件黑马王子7 小时前
13.缓存池优化:对象上限配置
开发语言·前端框架·c#
李迟7 小时前
Golang实践录:工程框架实践:搭建工程模板
开发语言·后端·golang
纪伊路上盛名在7 小时前
Kabsch算法的Julia实现
开发语言·算法·julia·序列分析·蛋白质·rmsd
玖玥拾7 小时前
Lua 基础语法(三) 元表 metatable、元方法、模拟面向对象
开发语言·unity·lua
维天说8 小时前
Agent会听人话,反而更难管
java·开发语言·人工智能
会飞的拖把8 小时前
Python 面向对象编程详解:从类与对象到动态属性方法
开发语言·python
大牧师8 小时前
Nest.js 微服务入门教程
开发语言·javascript·后端·微服务·node.js·nest.js·nest