量化交易之QT篇 - TQZButton - 自定义按钮
原创
©著作权归作者所有:来自51CTO博客作者ErwinSmith的原创作品,请联系作者获取转载授权,否则将追究法律责任
// TQZButton.h
#ifndef TQZBUTTON_H
#define TQZBUTTON_H
#include <QPushButton>
enum TQZButtonType {
COMMON,
CLOSE
};
class TQZButton : public QPushButton
{
Q_OBJECT
public:
explicit TQZButton(const QString &text, TQZButtonType buttonType , QWidget *parent = nullptr);
virtual ~TQZButton();
protected:
void enterEvent(QEvent* event);
void leaveEvent(QEvent* event);
private:
void UpdateSelf(const QString &text);
QMap<TQZButtonType, QMap<QString, QString> *>* GetButtonStyleConfig();
private:
QMap<TQZButtonType, QMap<QString, QString> *>* m_buttonStyleConfig;
TQZButtonType m_buttonType;
signals:
};
#endif // TQZBUTTON_H
// TQZButton.cpp
#include "TQZButton.h"
#include <QFont>
#include <QMouseEvent>
#include <QDebug>
TQZButton::TQZButton(const QString &text, TQZButtonType buttonType, QWidget *parent):
QPushButton(parent),
m_buttonStyleConfig(nullptr),
m_buttonType(buttonType)
{
this->UpdateSelf(text);
}
void TQZButton::UpdateSelf(const QString &text) {
this->setText(text);
this->setStyleSheet(GetButtonStyleConfig()->find(m_buttonType).value()->find("common").value());
}
void TQZButton::enterEvent(QEvent* event) {
this->setStyleSheet(GetButtonStyleConfig()->find(m_buttonType).value()->find("movein").value());
QPushButton::enterEvent(event);
}
void TQZButton::leaveEvent(QEvent* event) {
this->setStyleSheet(GetButtonStyleConfig()->find(m_buttonType).value()->find("common").value());
QPushButton::enterEvent(event);
}
QMap<TQZButtonType, QMap<QString, QString>*>* TQZButton::GetButtonStyleConfig() {
if (this->m_buttonStyleConfig == nullptr) {
this->m_buttonStyleConfig = new QMap<TQZButtonType, QMap<QString, QString>*>;
QMap<QString, QString> *commonButtonConfig = new QMap<QString, QString>;
commonButtonConfig->insert("common", "TQZButton { border: none; color: white; }");
commonButtonConfig->insert("movein", "TQZButton { border-radius: 6px; border: none; background-color: rgb(63, 60, 60); color: white; }");
QMap<QString, QString> *closeButtonConfig = new QMap<QString, QString>;
closeButtonConfig->insert("common", "TQZButton { border: none; color: white; }");
closeButtonConfig->insert("movein", "TQZButton { border-radius: 6px; border: none; background-color: rgb(228, 64, 50); color: white; }");
this->m_buttonStyleConfig->insert(COMMON, commonButtonConfig);
this->m_buttonStyleConfig->insert(CLOSE, closeButtonConfig);
}
return this->m_buttonStyleConfig;
}
TQZButton::~TQZButton() {
if (this->m_buttonStyleConfig != nullptr) {
foreach (const TQZButtonType &key, this->m_buttonStyleConfig->keys()) {
delete this->m_buttonStyleConfig->value(key);
this->m_buttonStyleConfig->insert(key, nullptr);
}
delete this->m_buttonStyleConfig;
this->m_buttonStyleConfig = nullptr;
}
}