QT图形界面文字、按钮设计应用实例

任务要求:
设计一个串口,有一个QLabel,两个QPushbutton。
当点击按钮1时让QLabel中文字在"你好"和"再见"之间切换。
当点击按钮2时让QLable中文字的颜色在绿色和红色之间切换。

QT工程的创建请跳转:https://blog.csdn.net/weixin_43793181/article/details/109519743

main.c

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    Widget w;

    w.resize(800,480);

    w.show();

    return a.exec();
}



widget.h

#ifndef WIDGET_H
#define WIDGET_H

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


class Widget : public QWidget
{
    
    
    Q_OBJECT

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

signals:
    void testclicked();

private slots:
   int myclicked1();
   int myclicked2();
   int myclicked3();

private:
   int string_flag = 0;
   int color_flag = 0;
   QLabel *lab;
   QPushButton *button1;
   QPushButton *button2;
   QPushButton *button3;

};

#endif // WIDGET_H



widget.cpp

#include "widget.h"
#include <QDebug>


Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    
    
    lab = new QLabel(this);
    button1 = new QPushButton("1",this);
    button2 = new QPushButton("2",this);
    button3 = new QPushButton("退出",this);

    button1->move(200,400);
    button2->move(500,400);
    button3->move(680,0);

    QObject::connect(button1,SIGNAL(clicked()),this,SLOT(myclicked1()));
    QObject::connect(button2,SIGNAL(clicked()),this,SLOT(myclicked2()));
    QObject::connect(button3,SIGNAL(clicked()),this,SLOT(myclicked3()));
}

int Widget :: myclicked1()
{
    
    
    if(string_flag == 0)
    {
    
    
        string_flag =1;
        lab->setText("你好!");
        lab->move(350,100);
        lab->resize(300,200);
        QFont font("Times",30,5,false);
        lab->setFont(font);

        QPalette p;
        QColor color(0,0,0);
        p.setColor(QPalette::WindowText,color);
        lab->setPalette(p);
        return 0;
    }

    else
    {
    
    
        string_flag = 0;
        lab->setText("再见!");
        lab->move(350,100);
        lab->resize(300,200);
        QFont font("Times",30,5,false);
        lab->setFont(font);

        QPalette p;
        QColor color(0,0,0);
        p.setColor(QPalette::WindowText,color);
        lab->setPalette(p);
        return 0;
    }
}

int Widget :: myclicked2()
{
    
    
    if(color_flag == 0)
    {
    
    
        QPalette p;
        QColor color(0,255,0);
        p.setColor(QPalette::WindowText,color);
        lab->setPalette(p);
        color_flag =1;
        return 0;
    }

    else
    {
    
    
        QPalette p;
        QColor color(255,0,0);
        p.setColor(QPalette::WindowText,color);
        lab->setPalette(p);
        color_flag = 0;
        return 0;
    }
}

int Widget :: myclicked3()
{
    
    
   exit(0);
}

Widget::~Widget()
{
    
    

}



程序运行会弹出如下窗口
在这里插入图片描述
接着按1,2,2,1,2,2,对应效果如下
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43793181/article/details/109520035