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

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

相关推荐
Wy_编程1 小时前
go语言面向对象和异常处理
开发语言·后端·golang
进击的荆棘1 小时前
C++起始之路——C++11(下)
开发语言·c++·c++11·lambda
许长安1 小时前
C++ 原子变量与内存序:从std::atomic到release/acquire
开发语言·数据结构·c++·经验分享·笔记
代码中介商3 小时前
C++ STL 容器完全指南(二):vector 深入与 stringstream 实战
开发语言·c++
郝学胜-神的一滴9 小时前
Qt 入门 01-01:从零基础到商业级客户端实战
开发语言·c++·qt·程序人生·软件构建
测试员周周10 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
摇滚侠10 小时前
@Autowired 和 @Resource 的区别
java·开发语言
Wy_编程10 小时前
go语言中的结构体
开发语言·后端·golang
SeaTunnel10 小时前
(八)收官篇 | 数据平台最后一公里:数据集成开发设计与上线治理实战
java·大数据·开发语言·白鲸开源