版权声明:本文为博主原创文章,欢迎各位朋友转载。转载时,保留链接地址! https://blog.csdn.net/naibozhuan3744/article/details/82151007
本博客主要总结一个自定义的按钮实例。该实例实现的效果是上面是图片、下面是文字,其中图片位置和文字位置任意可调。
该自定义控件的实现思路如下:
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(:/resource/icon/menu_sourceDiskMirror.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(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);
QMenuButton::setLayout(mainLayout);
}
1.2效果如下图所示:
参考内容: