自定義控件的實現思路如下:
a1.新建一個類,該類繼承QPushbutton,由於QPushbutton繼承於QWidget,因此可以直接在該繼承類里面進行布局管理和掛載控件;
a2.新建兩個QLabel實例,即buttonImage和buttonTxt(是QLable實例)。分別用兩個垂直布局管理器QVBoxLayout掛載,即topLayout和bottomLayout(QVBoxLayout的實例)掛載。
a3.然后新建一個垂直布局管理器mainLayout(QVBoxLayout的實例),用mainLayout將上面的兩個topLayout和bottomLayout掛載進來。
a4.然后該類就可以跟QPushbutton一樣調用了,只是這個按鈕比QPushbutton多了一個功能,那就是可以實現任意位置的上面圖片下面文字效果,其它功能跟QPushbutton一模一樣。
MyMenuButton::MyMenuButton(QString str_icon,QString str_text,int w,int h) { this->setFixedSize(w,h); //調整控件尺寸 QLabel *buttonImage = new QLabel(); buttonImage->setStyleSheet(str_icon); QLabel *buttonTxt = new QLabel(); buttonTxt->setFixedHeight(20); buttonTxt->setText(str_text); buttonTxt->setAlignment(Qt::AlignHCenter|Qt::AlignTop); QVBoxLayout *topLayout = new QVBoxLayout(); topLayout->addWidget(buttonImage); topLayout->setContentsMargins(10,10,10,0); QVBoxLayout *bottomLayout = new QVBoxLayout(); bottomLayout->addWidget(buttonTxt); bottomLayout->setMargin(0); bottomLayout->setSpacing(0); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(5); mainLayout->addLayout(topLayout); mainLayout->addLayout(bottomLayout); this->setLayout(mainLayout); }
---------------------
作者:凈無邪
來源:CSDN
原文:https://blog.csdn.net/naibozhuan3744/article/details/82151007
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!