本博客主要总结一个自定义的按钮实例。该实例实现的效果是上面是图片、下面是文字,其中图片位置和文字位置任意可调。
该自定义控件的实现思路如下:
a1.新建一个类,该类继承QPushbutton,由于QPushbutton继承于QWidget,因此可以直接在该继承类里面进行布局管理和挂载控件;
a2.新建两个QLabel实例,即buttonImage和buttonTxt(是QLable实例)。分别用两个垂直布局管理器QVBoxLayout挂载,即topLayout和bottomLayout(QVBoxLayout的实例)挂载。
a3.然后新建一个垂直布局管理器mainLayout(QVBoxLayout的实例),用mainLayout将上面的两个topLayout和bottomLayout挂载进来。
a4.然后该类就可以跟QPushbutton一样调用了,只是这个按钮比QPushbutton多了一个功能,那就是可以实现任意位置的上面图片下面文字效果,其它功能跟QPushbutton一模一样。
1.1具体的实例代码如下所示:
/*自定义菜单按钮类*/QMenuButton::QMenuButton(){QMenuButton::setFixedSize(120,90);QLabel *buttonImage = new QLabel();buttonImage->setStyleSheet("QLabel{border-image:url(:/1.png)}");QLabel *buttonTxt = new QLabel();buttonTxt->setFixedHeight(20);buttonTxt->setText(tr("测试按钮"));buttonTxt->setAlignment(Qt::AlignHCenter|Qt::AlignTop);QVBoxLayout *topLayout = new QVBoxLayout();topLayout->addWidget(buttonImage);topLayout->setContentsMargins(25,0,0,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);QMenuButton::setLayout(mainLayout);}
参考内容:
/Ten10/p/Ten15.html
/i80386/p/4587065.html