引言
之前在另一篇博文《Qt利用字体库实现图标的动态换肤》已经完成了字库的引入,实现两个基础的图标控件类IconButton和IconLabel,可以覆盖多数的使用场景,但随着重构的铺开还需要对其他频繁使用的控件进行封装,当然这些都是基于原有的基础上进行封装。
如上图所示,通过图标和文字的搭配进行提示展示,按照布局方式不同可分为四种,代码实现也是通过调整布局,较为简单。由于存在多个构造函数,为简化代码使用C++11的委托构造函数,也就是同一个类中一个构造函数可以调用另外一个构造函数。
完整代码
class IconTipsLabel : public QWidget
{
Q_OBJECT
public:
enum IconLayoutStyle {
ILS_TOP,
ILS_BOTTOM,
ILS_LEFT,
ILS_RIGHT,
};
explicit IconTipsLabel(int iconIndex, IconLayoutStyle layoutStyle, QWidget *parent = nullptr);
explicit IconTipsLabel(int iconIndex, QWidget *parent = nullptr);
explicit IconTipsLabel(IconLayoutStyle layoutStyle, QWidget *parent = nullptr);
void setIconSize(int size);
void setIconObjName(QString str);
void setTips(QString str);
void setTipsObjName(QString str);
QHBoxLayout* bottomLayout() { return m_bottomLayout; }
void setIconIndex(int iconIndex);
private:
IconLabel* m_iconLabel;
QLabel* m_tipsLabel;
QHBoxLayout* m_bottomLayout;
};
IconTipsLabel::IconTipsLabel(int iconIndex, IconTipsLabel::IconLayoutStyle layoutStyle, QWidget *parent)
: QWidget(parent)
{
m_iconLabel = new IconLabel(iconIndex, this);
m_iconLabel->setMinimumSize(40, 40);
m_tipsLabel = new QLabel(this);
m_bottomLayout = new QHBoxLayout;
QLayout* contextLyaout;
switch (layoutStyle) {
case ILS_TOP:
case ILS_BOTTOM:
contextLyaout = new QVBoxLayout;
if (layoutStyle == ILS_BOTTOM) {
contextLyaout->addWidget(m_tipsLabel);
contextLyaout->addWidget(m_iconLabel);
}
else {
contextLyaout->addWidget(m_iconLabel);
contextLyaout->addWidget(m_tipsLabel);
}
contextLyaout->setAlignment(m_iconLabel, Qt::AlignHCenter);
contextLyaout->setAlignment(m_tipsLabel, Qt::AlignHCenter);
break;
case ILS_LEFT:
contextLyaout = new QHBoxLayout;
contextLyaout->addWidget(m_iconLabel);
contextLyaout->addWidget(m_tipsLabel);
break;
case ILS_RIGHT:
contextLyaout = new QHBoxLayout;
contextLyaout->addWidget(m_tipsLabel);
contextLyaout->addWidget(m_iconLabel);
break;
}
auto mainLayout = new QVBoxLayout(this);
mainLayout->addStretch();
mainLayout->addLayout(contextLyaout);
mainLayout->addLayout(m_bottomLayout);
mainLayout->addStretch();
mainLayout->setAlignment(contextLyaout, Qt::AlignHCenter);
}
IconTipsLabel::IconTipsLabel(int iconIndex, QWidget *parent)
: IconTipsLabel(iconIndex, ILS_TOP, parent)
{
}
IconTipsLabel::IconTipsLabel(IconLayoutStyle layoutStyle, QWidget *parent)
: IconTipsLabel(IconFont::ICON_CAMERA, layoutStyle, parent)
{
m_iconLabel->hide();
}
void IconTipsLabel::setIconSize(int size)
{
m_iconLabel->setFixedSize(size, size);
}
void IconTipsLabel::setIconObjName(QString str)
{
m_iconLabel->setObjectName(str);
}
void IconTipsLabel::setTips(QString str)
{
m_tipsLabel->setText(str);
}
void IconTipsLabel::setTipsObjName(QString str)
{
m_tipsLabel->setObjectName(str);
}
void IconTipsLabel::setIconIndex(int iconIndex)
{
m_iconLabel->setIcon(iconIndex);
m_iconLabel->show();
}