Qt 中的自动排他工具按钮

autoexclusive tool buttons in Qt

在这里,我提出了另一个问题,这次是关于 Qt 工具按钮 AutoExclusive 属性。请在下面找到我的问题:

Q) 我有 4 个相互排斥的工具按钮,但我面临的问题是当我想取消选择所选按钮时它不允许我这样做(这是 Qt 中定义的行为)但我希望每个按钮相互排斥,并且可以在单击所选按钮时取消选择它。谁能帮我解决这个问题。编程示例更有帮助。

提前致谢 凯沙夫

我有类似的需求,最终为 QActions 开发了一个小容器,它的界面大致如下:

class ExclusiveActionGroup : public QObject
{
    Q_OBJECT
public:
    explicit ExclusiveActionGroup(QObject *parent = 0);
    QAction * addAction ( QAction * action );
    const QAction * checkedAction() const;
    void untrigger();

protected slots:
    void slotActionToggled(bool);

private:
    QList<QAction*> actions;
};

slotActionToggled 与添加的操作的切换功能挂钩,并处理组的排他性以及整个组的取消选择(未触发)。 请注意,slotActionToggled 可能会在取消选择相应的 QAction 的过程中被触发,因此您的代码应该处理这个(而不是再次切换 Action 触发 unggling which ...)

ADD-ON 完成实施:

#include "exclusiveactiongroup.h"
#include <QAction>

#if defined(_MSC_VER) && defined(_DEBUG)
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif // _MSC_VER

ExclusiveActionGroup::ExclusiveActionGroup(QObject *parent) :
    QObject(parent)
{
}

QAction * ExclusiveActionGroup::addAction ( QAction * action )
{
    actions.push_back(action);
    connect(action, SIGNAL(toggled(bool)), this, SLOT(slotActionToggled(bool)));
    return action;
}

void ExclusiveActionGroup::slotActionToggled ( bool checked )
{
    QAction* action = qobject_cast<QAction*>(sender());
    if (action && checked)
    {
        foreach(QAction* uncheck, actions)
        {
            if (uncheck != action)
            {
                uncheck->setChecked(false); // triggers recursion, doesnt matter though
            }
        }
    }
}

const QAction* ExclusiveActionGroup::checkedAction() const
{
    foreach(const QAction* a, actions)
    {
        if (a->isChecked())
        {
            return a;
        }
    }
    return 0;
}

void ExclusiveActionGroup::untrigger()
{
    foreach(QAction* a, actions)
    {
        if (a->isChecked())
        {
            a->trigger();
            break;
        }
    }
}