当前位置:   article > 正文

QLabel以及QWidget显示图片/来自主题的图标,并添加选中和hover效果_qss qlabel:hover右上角添加一个图标

qss qlabel:hover右上角添加一个图标

首先实现自己的label类:

myLabel.h:

  1. #ifndef MYLABEL_H
  2. #define MYLABEL_H
  3. #include <QEvent>
  4. #include <QLabel>
  5. class myLabel : public QLabel
  6. {
  7. public:
  8. myLabel();
  9. ~myLabel();
  10. void enterEvent(QEvent *e); //hover鼠标进入
  11. void leaveEvent(QEvent *e); //hover鼠标离开
  12. void mousePressEvent(QMouseEvent *e); //鼠标按下
  13. private:
  14. bool ifPressed;
  15. };
  16. #endif // MYLABEL_H

myLabel.cpp:

  1. #include "myLabel.h"
  2. #include <QPalette>
  3. myLabel::myLabel()
  4. {
  5. //setFrameShape(QFrame::Box); //先设置边框为矩形
  6. //setStyleSheet("border-width: 0px;");
  7. ifPressed = false;
  8. }
  9. myLabel::~myLabel()
  10. {
  11. }
  12. void myLabel::enterEvent(QEvent *e)
  13. {
  14. if(ifPressed == false)
  15. setStyleSheet("border-width: 4px;border-style: solid;border-color: rgb(220,20,60);");
  16. }
  17. void myLabel::leaveEvent(QEvent *e)
  18. {
  19. if(ifPressed == false)
  20. setStyleSheet("border-width: 0px;");
  21. }
  22. //鼠标按下
  23. void myLabel::mousePressEvent(QMouseEvent *e)
  24. {
  25. if(ifPressed == false)
  26. {
  27. ifPressed = true;
  28. QColor highLightColor = palette().color(QPalette::Highlight);
  29. QString stringColor = QString("rgb(%1,%2,%3)")
  30. .arg(highLightColor.red())
  31. .arg(highLightColor.green())
  32. .arg(highLightColor.blue());
  33. QString stringStyleSheet = QString("border-width: 4px;border-style: solid;border-color: %1;").arg(stringColor);
  34. setStyleSheet(stringStyleSheet);
  35. }
  36. else
  37. {
  38. ifPressed = false;
  39. setStyleSheet("border-width: 0px;");
  40. }
  41. }

这里用QColor获取了palette调色板的颜色,并用QString的方式进行设置(也许有更简单的方式实现。。。。我直接用palette不行)。

mainwindow.cpp部分代码:

  1. ui->setupUi(this);
  2. myLabel *pic = new myLabel;
  3. pic -> setParent(this);
  4. pic->setGeometry(rect().x()+80, rect().y()+30,400, 400);
  5. QPixmap pix("/home/kylin-fc/image/123.png");
  6. pic->setPixmap(pix);
  7. //pic->setPixmap(QPixmap::fromImage(QIcon::fromTheme("ukui-control-center").pixmap(24,24).toImage()));

完整项目地址:

https://download.csdn.net/download/IT8343/15840250?spm=1001.2014.3001.5503

附Qwidget显示图片:

  1. QSize IMAGE_SIZE(381, 221);
  2. ui->previewWidget->setAutoFillBackground(true);
  3. QPalette palette;
  4. palette.setBrush(QPalette::Background, QBrush(QPixmap("/home/kylin-fc/TEMP.bmp").scaled(IMAGE_SIZE)));
  5. ui->previewWidget->setPalette(palette);
  6. /*显示屏保
  7. QStringList args;
  8. QString screensaver_bin = "/usr/lib/ukui-screensaver/ukui-screensaver-default";
  9. args << "-window-id" << QString::number(ui->previewWidget->winId());
  10. process->startDetached(screensaver_bin, args);
  11. */

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/292743
推荐阅读
  

闽ICP备14008679号