实现普通按钮+底部线条组合成的按钮。
使用QPushButton(按钮)和QLabel(底部线条)组合实现。
class Line : public QLabel {
Q_OBJECT
public:
Line(QWidget *parent = NULL) : QLabel(parent) { }
/* 绘图事件 */
void paintEvent(QPaintEvent *)
{
QPainter painter(this);
/* 设置画笔 */
painter.setPen(QPen(Qt::black, height()));
/* 画线 */
painter.drawLine(0, 0, width(), 0);
}
};
class Button : public QPushButton {
Q_OBJECT
public:
Button(const QString &text, QWidget *parent = NULL) :
QPushButton(text, parent)
{
m_line = new Line(this);
m_line->setVisible(false);
QString styleSheet = R"(
QPushButton {
border: 0px;
border-radius: 5px;
margin: 0px;
padding: 0px;
font-size: 16px;
background: white;
color: black;
outline: none;
}
QPushButton:pressed{
outline: none;
background: #1ABC9C;
color: white;
}
)";
this->setStyleSheet(styleSheet);
}
void focusInEvent(QFocusEvent *)
{
/* 焦点进入则显示底部线条 */
m_line->setVisible(true);
}
void focusOutEvent(QFocusEvent *)
{
/* 焦点离开则隐藏底部线条 */
m_line->setVisible(false);
}
void resizeEvent(QResizeEvent *event)
{
/* 按按钮大小变化时ye也要自动适应其底部线条的大小与位置 */
m_line->resize(event->size().width()*0.75, 5);
int lineX = (event->size().width() - m_line->width())/2;
int lineY = event->size().height() * 0.85;
m_line->move(lineX, lineY);
}
private:
Line *m_line;
};
QHBoxLayout *layout = new QHBoxLayout;
for (int i = 0; i < 5; i++) {
Button *btn = new Button(QString::fromLocal8Bit("标题") + QString::number(i+1));
btn->setFixedSize(80, 50);
layout->addWidget(btn);
}
QWidget w;
w.setWindowTitle(QString::fromLocal8Bit("按钮栏@Qt君"));
w.setLayout(layout);
w.show();
完整运行源码可以回复"入群",后再群文件获取。