Cantonese embedded C++, QT window button operation

Operation:

Design a window with 2 buttons and 1 label

Click button 1 to switch the label text between "Hello" and "Goodbye"

Click button 2 to switch the label text color between red and blue

//这是.h文件
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>
#include <QLabel>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private slots:
    //

private:
    QPushButton *btn;
    QPushButton *btn1;
    QLabel *lab;



    int flag =0;
    int flag1 =0;
};
#endif // WIDGET_H
//.cpp文件
#include "widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
        btn = new QPushButton("点击",this);
        btn1 = new QPushButton("点击1",this);
        lab = new QLabel("hello",this);

        btn->move(300,150);
        btn1->move(150,150);
        lab->move(100,50);



        QObject::connect(btn,&QPushButton::clicked,this,[&](){

            if(flag == 0){

                    lab->setText("hallo");
                    flag = 1;

                }
            else if(flag == 1){

                    lab->setText("buy");
                    flag = 0;

                }

        });
        QObject::connect(btn1,&QPushButton::clicked,this,[&](){

            if(flag1 == 0){
                QColor c(0,0,255);//大红
                QPalette p;//调色板
                p.setColor(QPalette::WindowText/*文本颜色*/,c);
                lab->setPalette(p);//设置调色板
                    flag1 = 1;

                }
            else if(flag1 == 1){
                QColor c(255,0,0);//大红
                QPalette p;//调色板
                p.setColor(QPalette::WindowText/*文本颜色*/,c);
                lab->setPalette(p);//设置调色板

                    flag1 = 0;

                }


        });

}

Widget::~Widget()
{
}

 

Guess you like

Origin blog.csdn.net/weixin_44359952/article/details/127394620