date:
updated:
Qt实现自定义图标功能

作者:hackett
微信公众号:加班猿
在上一节的基础上进行定义图标的功能
参考上一节的链接:Qt无边框窗口拖拽和阴影
效果:要做的是应用的放大缩小、最小化功能,鼠标移动和点击图标变色

准备工作:
控件:
3个PushButton
1个Label
1个Frame
注意:需要进行布局,如果不布局可能会出现不能放大缩小的情况

准备图标嵌入控件
可以上阿里巴巴矢量图标库下载自己想要的图标,也可以去其他网站或者自己制作
我这里下载了三个图标

QSS样式表
右键选择改变样式表,其他按键同理
添加颜色:
QPushButton为改变这个按钮的属性
QPushButton:hover为鼠标移动到按键的效果
QPushButton:pressed为鼠标按下按键的效果
添加资源:
可以选择我们资源里面的图片为按键填充图片

接下来就可以链接到槽函数做相应的处理即可
放大缩小按钮需要做下margin值的设置
1 2 3 4 5 6 7 8 9 10 11 12
| void Widget::on_buttonMax_clicked() { if(this->isMaximized()) { ui->vLayout->setMargin(9); this->showNormal(); }else { ui->vLayout->setMargin(0); this->showMaximized(); } }
|

源码:
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12
| #include "widget.h" #include <QApplication>
int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show();
return a.exec(); }
|
widget.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include "widget.h" #include "ui_widget.h" #include <QMouseEvent> #include <QWidget> #include <QGraphicsDropShadowEffect>
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint);
QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
shadow->setBlurRadius(5); shadow->setColor(Qt::black); shadow->setOffset(0);
ui->shadowWidget->setGraphicsEffect(shadow);
this->setAttribute(Qt::WA_TranslucentBackground); }
Widget::~Widget() { delete ui; }
void Widget::mouseMoveEvent(QMouseEvent *event) { if(this->z == QPoint()) return; QPoint y = event->globalPos(); QPoint x = y - this->z; this->move(x); }
void Widget::mousePressEvent(QMouseEvent *event) { QPoint y = event->globalPos(); QPoint x = this->geometry().topLeft(); this->z = y - x; }
void Widget::mouseReleaseEvent(QMouseEvent *event) { this->z = QPoint(); }
void Widget::on_buttonClose_clicked() { this->close(); }
void Widget::on_buttonMax_clicked() { if(this->isMaximized()) { ui->vLayout->setMargin(9); this->showNormal(); }else { ui->vLayout->setMargin(0); this->showMaximized(); } }
void Widget::on_buttonMin_clicked() { this->showMinimized(); }
|
widget.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #ifndef WIDGET_H #define WIDGET_H
#include <QWidget>
namespace Ui { class Widget; }
class Widget : public QWidget { Q_OBJECT
public: explicit Widget(QWidget *parent = 0); ~Widget();
virtual void mouseMoveEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event);
private slots: void on_buttonClose_clicked();
void on_buttonMax_clicked();
void on_buttonMin_clicked();
private: Ui::Widget *ui; QPoint z; };
#endif
|
如果你觉得文章还不错,记得”点赞关注“
关注我的微信公众号【 加班猿 】可以获取更多内容
