自由发挥实现一个登录窗口的应用场景
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QPen>
#include <QBrush>
#include <QPainter>
#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
class Painter;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();protected:void paintEvent(QPaintEvent* event);void timerEvent(QTimerEvent* event);private slots:void on_pushButton_clicked();private:Ui::Widget *ui;int bY = 70;int gY = 20;int rY = 120;bool bUp = false;bool gUp = false;bool rUp = false;
};class Painter
{
private:QPen pen;QBrush brush;QPainter painter;public:Painter(Widget* widget);void setColor(QColor color);void drawRect(int x, int y, int w, int h);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "./ui_widget.h"
#include <QMessageBox>Painter::Painter(Widget* widget): painter(widget)
{brush.setStyle(Qt::SolidPattern);
}void Painter::drawRect(int x, int y, int w, int h)
{painter.drawRect(x, y, w, h);
}void Painter::setColor(QColor color)
{pen.setColor(color);brush.setColor(color);painter.setPen(pen);painter.setBrush(brush);
}Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);this->resize(400, 400);this->startTimer(30);
}Widget::~Widget()
{delete ui;
}void Widget::paintEvent(QPaintEvent* event)
{Q_UNUSED(event);Painter painter(this);if (bUp){painter.setColor(QColor(0, 0, 255, 255));painter.drawRect(100, bY, 200, 50);}if (gUp){painter.setColor(QColor(0, 255, 0, 255));painter.drawRect(100, gY, 200, 50);}if (rUp){painter.setColor(QColor(255, 0, 0, 255));painter.drawRect(100, rY, 200, 50);}if (!bUp){painter.setColor(QColor(0, 0, 255, 255));painter.drawRect(100, bY, 200, 50);}if (!gUp){painter.setColor(QColor(0, 255, 0, 255));painter.drawRect(100, gY, 200, 50);}if (!rUp){painter.setColor(QColor(255, 0, 0, 255));painter.drawRect(100, rY, 200, 50);}painter.setColor(QColor(240, 240, 240, 255));painter.drawRect(100, 145, 200, 50);if (!bUp){bY += 1;if (122 == bY){bUp = true;}}else{bY -= 1;if (bY + 49 == rY){bUp = false;}}if (!gUp){gY += 1;if (122 == gY){gUp = true;}}else{gY -= 1;if (gY + 50 == bY){gUp = false;}}if (!rUp){rY += 1;if (122 == rY){rUp = true;}}else{rY -= 1;if (rY + 50 == gY){rUp = false;}}
}void Widget::timerEvent(QTimerEvent* event)
{Q_UNUSED(event);this->update();
}void Widget::on_pushButton_clicked()
{QString user = ui->user_lineEdit->text();QString passwd = ui->passwd_lineEdit->text();if ("lkjhxx" == user && "123456" == passwd){QMessageBox::information(NULL, "提示", "登录成功!", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);}else{QMessageBox::information(NULL, "提示", "登录失败!", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);}
}
效果