#include "myiconbutton.h" #include #include #include #include #include // #include "imageutil.h" #include "../gsettingswrapper.h" MyIconButton::MyIconButton(QWidget *parent) : QPushButton(parent) { this->setCheckable(false); m_iconButton = new QPushButton(this); m_iconButton->setCheckable(true); m_iconButton->setFixedSize(QSize(24, 24)); m_iconButton->setFocusPolicy(Qt::NoFocus); m_iconButton->setFlat(true); m_textLabel = new MyLabel(this); QSizePolicy textLabelPolicy = m_textLabel->sizePolicy(); textLabelPolicy.setHorizontalPolicy(QSizePolicy::Fixed); textLabelPolicy.setVerticalPolicy(QSizePolicy::Fixed); m_textLabel->setSizePolicy(textLabelPolicy); // m_textLabel->setScaledContents(true); QHBoxLayout *hLayout = new QHBoxLayout(); hLayout->setContentsMargins(8, 0, 0, 0); hLayout->addWidget(m_iconButton, Qt::AlignCenter); hLayout->addWidget(m_textLabel); hLayout->addStretch(); setLayout(hLayout); connect(m_iconButton, &QPushButton::clicked, this, &MyIconButton::click); } MyIconButton::~MyIconButton() {} void MyIconButton::setThemeIcon(const QString &themeIconName, const QString &defaultIconName, int size) { m_themeIconName = themeIconName; m_defaultIconName = defaultIconName; QIcon icon = QIcon::fromTheme(themeIconName, QIcon(defaultIconName)); m_iconButton->setIcon(icon.pixmap(icon.actualSize(QSize(size, size)))); } void MyIconButton::setDesplayText(const QString &text) { m_originalText = text; m_textLabel->setDeplayText(text); } void MyIconButton::changePalette(bool checked) { m_iconButton->setChecked(checked); QPalette pal = m_textLabel->palette(); // png格式的图标会自动跟随主题,不需再手动设置像素颜色 if (g_GSettingWrapper.isDarkTheme()) { if (checked) { pal.setColor(QPalette::ButtonText, this->palette().highlightedText().color()); } else { pal.setColor(QPalette::ButtonText, this->palette().windowText().color()); } } else { if (checked) { pal.setColor(QPalette::ButtonText, this->palette().highlightedText().color()); } else { pal.setColor(QPalette::ButtonText, this->palette().windowText().color()); } } m_textLabel->setPalette(pal); } void MyIconButton::paintEvent(QPaintEvent *event) { QPushButton::paintEvent(event); changePalette(isChecked()); m_textLabel->setFixedWidth(this->width() - 38); m_textLabel->setDeplayText(m_originalText); }