自定义Qt按钮

时间:2023-03-08 17:45:24

转自:http://blog.****.net/starcloud_zxt/article/details/5185556

Qt自带的PushButton样式比较单一,在开发的时候往往按钮的形状各异,所以需要自定义Qt的按钮。其方法是做一张图片来作为按钮,如果需要动态效果的话,可以做两张图片进行替换。按钮的载体可以是QLabel、QPushButton,可以通过QStyle类来设计样式,如果对QStyle不太了解的话,可以用下面的方法来实现。

1. 使用QPushButton

通过自定义一个按钮样式函数,在该函数中设置按钮的样式。(可以设计一个QPushButton的子类来完成设置)

实现代码:

  1. QPushButton *custButton(QString str,QString str1)
  2. {
  3. QPushButton *pushButton= new QPushButton;
  4. pushButton->setGeometry(10,10,200,200); //按钮的位置及大小
  5. pushButton->clearMask();
  6. pushButton->setBackgroundRole( QPalette::Base);
  7. QPixmap mypixmap;   mypixmap.load(str);
  8. pushButton->setFixedSize( mypixmap.width(), mypixmap.height() );
  9. pushButton->setMask(mypixmap.createHeuristicMask());
  10. pushButton->setIcon(mypixmap);
  11. pushButton->setIconSize(QSize(mypixmap.width(),mypixmap.height()));
  12. pushButton->setToolTip(str1);
  13. return pushButton;
  14. }

调用代码:

  1. QPushButton *btn=custButton("../login.png", "LOGIN");
  2. connect(btn, SIGNAL(clicked()), this, SLOT(slotLogin()));

2. 通过QLabel

我们可以把一个图片放在QLabel里面作为按钮,因为我没有找到QLabel是否有当点击后发出的信号,所以自定义了一个鼠标事件用来检测是否在QLabel上点击了鼠标。在自定义的鼠标事件中检测QLabel所在的区域,当在该区域发生鼠标点击事件后,发送信号。

设计时通过Qt Creator在widget.ui中加入一个QLabel即可,不需要进行设置。

代码widget.h

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3. #include <QWidget>
  4. namespace Ui {
  5. class Widget;
  6. }
  7. class Widget : public QWidget {
  8. Q_OBJECT
  9. public:
  10. Widget(QWidget *parent = 0);
  11. ~Widget();
  12. signals:
  13. void clicked();
  14. protected:
  15. void mousePressEvent(QMouseEvent *e);
  16. protected slots:
  17. void slotClicked();
  18. private:
  19. Ui::Widget *ui;
  20. };
  21. #endif // WIDGET_H

代码widget.cpp

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3. #include <QMouseEvent>
  4. #include <QMessageBox>
  5. #include <QPixmap>
  6. #include <QLabel>
  7. Widget::Widget(QWidget *parent) :
  8. QWidget(parent),
  9. ui(new Ui::Widget)
  10. {
  11. ui->setupUi(this);
  12. //使用label作为按钮,通过自定义鼠标事件,点击label所在区域实现鼠标单击
  13. QPixmap pm;   pm.load("../logo.png");
  14. ui->label->setGeometry(0,0,pm.width(), pm.height());
  15. ui->label->setPixmap(pm);
  16. connect( this, SIGNAL(clicked()), this, SLOT(slotClicked()));   //信号连接
  17. }
  18. Widget::~Widget()
  19. {
  20. delete ui;
  21. }
  22. void Widget::mousePressEvent(QMouseEvent *e)
  23. {
  24. int x = e->x();
  25. int y = e->y();
  26. //假如在QRect( 0, 0, 48, 48 )这个区域里(图片大小为48X48),就发出信号
  27. if (x>0 && x<48 && y>0 && y<48){
  28. emit clicked();
  29. }
  30. }
  31. void Widget::slotClicked()
  32. {
  33. QMessageBox::about( this, "Mouse Example", "You have pressed mouse, exit now!");
  34. close();
  35. }