一、概述
案例:編寫一個自定義按鈕。要求:1.給按鈕添加自定義背景 2.監聽按鈕點擊事件
二、代碼案例
1.創建一個類讓其繼承QWidget,點擊下一步下一步最后完成
2.打開MyPushButton,讓其繼承QPushButton。如下所示:
MyPushButton::MyPushButton(QWidget *parent) : QPushButton(parent)
{
}
3.重載其構造函數,讓其傳入按鈕背景圖片的路徑。可設按鈕的固定尺寸大小、icon、樣式等。設置完成后這個自定義按鈕就完成了。
MyPushButton::MyPushButton(QString normalImg,QString pressImg){ normalImgPath = normalImg; pressedImgPath = pressImg; QPixmap pixmap; //判斷是否能正常加載圖片,若不能則提示用戶 bool ret = pixmap.load(normalImgPath); if(!ret){ qDebug() << normalImg <<"加載圖片失敗" ; } //設置圖片固定尺寸 this->setFixedSize(pixmap.width(),pixmap.height()); //設置不規則圖片的樣式表 this->setStyleSheet("QPushButton{border:0px}"); //設置圖標 this->setIcon(pixmap); //設置圖標大小 this->setIconSize(QSize(pixmap.width(),pixmap.height())); }
4.新建一個window類進行測試,在測試類的構造方法中加入如下的代碼,並使用信號和槽函數監聽按鈕的點擊事件
//創建開始按鈕 MyPushButton *startBtn = new MyPushButton(":/res/MenuSceneStartButton.png"); startBtn->setParent(this); startBtn->move(this->width()*0.5-startBtn->width()*0.5,this->height()*0.7); //連接信號槽,監聽開始按鈕點擊 connect(startBtn,&MyPushButton::clicked,[=](){ //點擊自定義按鈕的時候這個代碼塊的代碼會執行。 });
案例如下圖所示:一個圓潤的開始按鈕