前提
QToolButton* button = new QToolButton;
button->setCheckable(true);
QToolButtonでチェック可能にする
1. OFFにされそうになったら即戻す
connect(button, &QToolButton::toggled, this,
[button](bool checked)
{
if (!checked) {
// ユーザー操作による解除を拒否
button->setChecked(true);
}
});
2. mousePressEvent をオーバーライド
class LockOnToolButton : public QToolButton
{
Q_OBJECT
public:
using QToolButton::QToolButton;
protected:
void mousePressEvent(QMouseEvent* e) override
{
// すでにチェック済みなら何もしない
if (isCheckable() && isChecked())
return;
QToolButton::mousePressEvent(e);
}
};
特徴
- クリック自体を無視
- 解除用のシグナルも飛ばない
- 状態遷移が完全に制御できる
プログラムから解除したい場合
button->blockSignals(true);
button->setChecked(false);
button->blockSignals(false);