现在的web发展越来越快,很多流行的布局样式,都是从web开始的,写惯了Qt widgets 项目,很多时候想改进一下现有的人机交互,尤其是在现有的按钮上加一些动画的效果,例如鼠标移上去变大,移开还原。
Qt编写自定义控件还是非常方便和非常强大的,数量掌握Qpainter的各种绘制,自定义任意控件几乎都不是难题,只有想不到,没有做不到。
贴一张个人认为做的比较炫的UI界面:
如果工控项目的界面能够做到这种程序,应该可以让人眼前一亮。
运行效果图:
核心代码:
void AnimationButton::paintEvent(QPaintEvent *) { if (image.isEmpty()) { return; } QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); QPixmap pix(image); pix = pix.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); if (enter || leave) { int pixX = rect().center().x() - targetWidth / 2; int pixY = rect().center().y() - targetHeight / 2 - 10; QPoint point(pixX, pixY); painter.drawPixmap(point, pix); painter.drawText(QRectF(0, height() - 20, width(), 20), Qt::AlignCenter, text); } }
完整代码:
animationbutton.h
#ifndef ANIMATIONBUTTON_H #define ANIMATIONBUTTON_H /** * 作者:feiyangqingyun(QQ:517216493) 2016-10-22 * 1:可设置显示的图像和底部的文字 */ #include <QWidget> #include <QVariant> class QPropertyAnimation; class AnimationButton : public QWidget { Q_OBJECT public: explicit AnimationButton(QWidget *parent = 0); ~AnimationButton(); protected: void enterEvent(QEvent *); void leaveEvent(QEvent *); void paintEvent(QPaintEvent *); private: bool enter; //是否进入 bool leave; //是否离开 int pixWidth; //图片宽度 int pixHeight; //图片高度 int oldWidth; //图片旧宽度 int oldHeight; //图片旧高度 QPropertyAnimation *enterAnimation; //进入动画 QPropertyAnimation *leaveAnimation; //离开动画 int targetWidth; //目标宽度 int targetHeight; //目标高度 QString text; //显示文字 QString image; //图像路径 private slots: void enterImageChanged(QVariant index); void leaveImageChanged(QVariant index); public slots: //设置显示的文字 void setText(QString text); //设置显示的图像 void setImage(QString image); }; #endif // ANIMATIONBUTTON_H