赞
踩
效果图如下:
实现方式:
①最开始一直以为是在按钮下面弄一个QLabel之类的控件用来设置底部颜色,这样是可以实现,但是实现起来会比较复杂(需要在响应按钮点击事件、鼠标滑过事件的时候,这只QLabel的颜色,然后鼠标点击到另一个按钮的时候,需要清除上一个按钮的颜色)。
②比较简单的办法是直接使用QSS,可以直接设置按钮的底部边框宽度和颜色,这样就只需要在QSS中就能完成所有效果设置。
代码如下:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QButtonGroup> class Widget : public QWidget { Q_OBJECT private: QPushButton* btn1; QPushButton* btn2; QPushButton* btn3; QButtonGroup* btnGroup; QHBoxLayout* btnLayout; QVBoxLayout* mainLayout; public: Widget(QWidget *parent = nullptr); ~Widget(); }; #endif // WIDGET_H
#include "UnderlineButton.h" Widget::Widget(QWidget *parent) : QWidget(parent) { try { btn1=new QPushButton; btn2=new QPushButton; btn3=new QPushButton; btnGroup=new QButtonGroup; btnLayout=new QHBoxLayout; mainLayout=new QVBoxLayout; btnGroup->addButton(btn1); btnGroup->addButton(btn2); btnGroup->addButton(btn3); btn1->setFixedSize(100,40); btn2->setFixedSize(100,40); btn3->setFixedSize(100,40); btn1->setText(QStringLiteral("BTN1")); btn2->setText(QStringLiteral("BTN2")); btn3->setText(QStringLiteral("BTN3")); btn1->setObjectName("btn1"); btn2->setObjectName("btn2"); btn3->setObjectName("btn3"); btn1->setCheckable(true); btn1->setChecked(true); btn2->setCheckable(true); btn3->setCheckable(true); connect(btn1,&QPushButton::clicked,this,[=](bool){ foreach(QAbstractButton *btn,btnGroup->buttons()){ if(btn->objectName()=="btn1"){ btn->setChecked(true); } else{ btn->setChecked(false); } } }); connect(btn2,&QPushButton::clicked,this,[=](bool){ foreach(QAbstractButton *btn,btnGroup->buttons()){ if(btn->objectName()=="btn2"){ btn->setChecked(true); } else{ btn->setChecked(false); } } }); connect(btn3,&QPushButton::clicked,this,[=](bool){ foreach(QAbstractButton *btn,btnGroup->buttons()){ if(btn->objectName()=="btn3"){ btn->setChecked(true); } else{ btn->setChecked(false); } } }); this->setStyleSheet("QPushButton#btn1,QPushButton#btn2,QPushButton#btn3" "{background:transparent;border:none;color:#000000;}" "QPushButton#btn1:checked,QPushButton#btn2:checked,QPushButton#btn3:checked" "{background:transparent;border:none; border-bottom:3px solid #3598db;color:#3598db;}" "QPushButton#btn1:hover,QPushButton#btn2:hover,QPushButton#btn3:hover" "{background:transparent;border:none; border-bottom:3px solid #7598db;color:#7598db;}"); btnLayout->setMargin(0); btnLayout->setSpacing(5); btnLayout->addWidget(btn1); btnLayout->addWidget(btn2); btnLayout->addWidget(btn3); btnLayout->addStretch(1); mainLayout->setMargin(10); mainLayout->addStretch(1); mainLayout->addLayout(btnLayout); mainLayout->addStretch(1); setLayout(mainLayout); } catch (...) {} } Widget::~Widget() { }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。