这是一个自定义的HighlightableAction
类,继承自QAction
。以下是完整的头文件代码:
#ifndef HIGHLIGHTABLEACTION_H
#define HIGHLIGHTABLEACTION_H
#include <QAction>
#include <QPainter>
class HighlightableAction : public QAction {
public:
HighlightableAction(const QString& text, QObject* parent = nullptr)
: QAction(text, parent) {}
protected:
void connectNotify(const QMetaMethod& signal) override {
// 当按钮状态发生改变时,重新绘制
if (signal == QMetaMethod::fromSignal(&QAction::changed)) {
update();
}
QAction::connectNotify(signal);
}
void draw(QPainter* painter) override {
if (isChecked() || isDown()) {
// 按钮被按下或选中时,设置为灰色背景,并向上突出一点
painter->save();
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(200, 200, 200)); // 灰色背景颜色
QRectF rect = QRectF(geometry().topLeft(), QSizeF(geometry().width(), geometry().height() + 2));
painter->drawRect(rect);
painter->restore();
}
QAction::draw(painter);
}
};
#endif // HIGHLIGHTABLEACTION_H
这个类重写了connectNotify()
和draw()
方法,在按钮状态发生改变时重新绘制按钮。当按钮被按下或选中时,设置灰色背景并稍微向上突出。
请注意在使用此头文件时要包含相应的Qt库头文件,例如<QAction>
和<QPainter>
。
内容由零声教学AI助手提供,问题来源于学员提问