轉自:http://blog.csdn.net/starcloud_zxt/article/details/5185556
Qt自帶的PushButton樣式比較單一,在開發的時候往往按鈕的形狀各異,所以需要自定義Qt的按鈕。其方法是做一張圖片來作為按鈕,如果需要動態效果的話,可以做兩張圖片進行替換。按鈕的載體可以是QLabel、QPushButton,可以通過QStyle類來設計樣式,如果對QStyle不太了解的話,可以用下面的方法來實現。
1. 使用QPushButton
通過自定義一個按鈕樣式函數,在該函數中設置按鈕的樣式。(可以設計一個QPushButton的子類來完成設置)
實現代碼:
- QPushButton *custButton(QString str,QString str1)
- {
- QPushButton *pushButton= new QPushButton;
- pushButton->setGeometry(10,10,200,200); //按鈕的位置及大小
- pushButton->clearMask();
- pushButton->setBackgroundRole( QPalette::Base);
- QPixmap mypixmap; mypixmap.load(str);
- pushButton->setFixedSize( mypixmap.width(), mypixmap.height() );
- pushButton->setMask(mypixmap.createHeuristicMask());
- pushButton->setIcon(mypixmap);
- pushButton->setIconSize(QSize(mypixmap.width(),mypixmap.height()));
- pushButton->setToolTip(str1);
- return pushButton;
- }
調用代碼:
- QPushButton *btn=custButton("../login.png", "LOGIN");
- connect(btn, SIGNAL(clicked()), this, SLOT(slotLogin()));
2. 通過QLabel
我們可以把一個圖片放在QLabel里面作為按鈕,因為我沒有找到QLabel是否有當點擊后發出的信號,所以自定義了一個鼠標事件用來檢測是否在QLabel上點擊了鼠標。在自定義的鼠標事件中檢測QLabel所在的區域,當在該區域發生鼠標點擊事件后,發送信號。
設計時通過Qt Creator在widget.ui中加入一個QLabel即可,不需要進行設置。
代碼widget.h
- #ifndef WIDGET_H
- #define WIDGET_H
- #include <QWidget>
- namespace Ui {
- class Widget;
- }
- class Widget : public QWidget {
- Q_OBJECT
- public:
- Widget(QWidget *parent = 0);
- ~Widget();
- signals:
- void clicked();
- protected:
- void mousePressEvent(QMouseEvent *e);
- protected slots:
- void slotClicked();
- private:
- Ui::Widget *ui;
- };
- #endif // WIDGET_H
代碼widget.cpp
- #include "widget.h"
- #include "ui_widget.h"
- #include <QMouseEvent>
- #include <QMessageBox>
- #include <QPixmap>
- #include <QLabel>
- Widget::Widget(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::Widget)
- {
- ui->setupUi(this);
- //使用label作為按鈕,通過自定義鼠標事件,點擊label所在區域實現鼠標單擊
- QPixmap pm; pm.load("../logo.png");
- ui->label->setGeometry(0,0,pm.width(), pm.height());
- ui->label->setPixmap(pm);
- connect( this, SIGNAL(clicked()), this, SLOT(slotClicked())); //信號連接
- }
- Widget::~Widget()
- {
- delete ui;
- }
- void Widget::mousePressEvent(QMouseEvent *e)
- {
- int x = e->x();
- int y = e->y();
- //假如在QRect( 0, 0, 48, 48 )這個區域里(圖片大小為48X48),就發出信號
- if (x>0 && x<48 && y>0 && y<48){
- emit clicked();
- }
- }
- void Widget::slotClicked()
- {
- QMessageBox::about( this, "Mouse Example", "You have pressed mouse, exit now!");
- close();
- }