Qt 自定义按钮

自定义控件的实现思路如下:

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
版权声明:本文为博主原创文章,转载请附上博文链接!

转载于:https://www.cnblogs.com/nanqiang/p/10477680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值