Как я могу реализовать кнопку, которая содержит действие (QAction) и может соединиться с ним во время разработки в QtDesigner? - PullRequest
7 голосов
/ 11 ноября 2010

Я хочу использовать подход, когда большинство команд приложения выполняются в QActions, чтобы я мог легко перетаскивать действия в меню, панель инструментов, кнопку или что-нибудь еще.Итак, мне нужно реализовать такую ​​кнопку.Легко написать какой-нибудь класс, который будет держать его, взять из него значок, текст, ярлык и всплывающую подсказку и подключить clicked () к triggered ().Но я даже не могу заставить свойство кнопки «действие» в конструкторе.Похоже, что в редакторе его свойств могут отображаться только типы QVariant.

НО!Тролли сделали это как-то, поэтому задача должна быть выполнимой.Итак, есть предложения?

Ответы [ 4 ]

7 голосов
/ 11 ноября 2010

Я не уверен, но я понимаю, что у вас есть действие (созданное с помощью QtDesigner ), и вы хотите связать это действие с меню, кнопкой на панели инструментов и обычной кнопкой.

С QtDesigner легко использовать QAction в качестве пункта меню и кнопки панели инструментов.

Если вы хотите использовать это QAction также с обычной кнопкой, я думаю, вы не сможете сделать это только с Qt Designer .

Я предлагаю добавить в вашу форму: QtDesigner a QToolButton.

В своем конструкторе класса вы можете сообщить QToolButton, что он подключен к вашему QAction с помощью setDefaultAction () .

ui->toolButton->setDefaultAction(ui->actionHello);

Возможно, вам придется соответствующим образом изменить геометрию QToolButton.

Теперь, если вы нажмете на нее, будет запущено действие actionHello.

5 голосов
/ 24 августа 2014

Просто добавьте сюда для тех, кто ищет подобное решение

https://qt -project.org / вики / PushButton_Based_On_Action

Заголовок

#ifndef ACTIONBUTTON_H
#define ACTIONBUTTON_H

#include <QPushButton>
#include <QAction>

/*!
  *\brief An extension of a QPushButton that supports QAction.
  * This class represents a QPushButton extension that can be
  * connected to an action and that configures itself depending
  * on the status of the action.
  * When the action changes its state, the button reflects
  * such changes, and when the button is clicked the action
  * is triggered.
  */
class ActionButton : public QPushButton
{
    Q_OBJECT

private:

    /*!
      * The action associated to this button.
      */
    QAction* actionOwner;


public:
    /*!
      * Default constructor.
      * \param parent the widget parent of this button
      */
    explicit ActionButton(QWidget *parent = 0);

    /*!
      * Sets the action owner of this button, that is the action
      * associated to the button. The button is configured immediatly
      * depending on the action status and the button and the action
      * are connected together so that when the action is changed the button
      * is updated and when the button is clicked the action is triggered.
      * \param action the action to associate to this button
      */
    void setAction( QAction* action );


signals:

public slots:
    /*!
      * A slot to update the button status depending on a change
      * on the action status. This slot is invoked each time the action
      * "changed" signal is emitted.
      */
    void updateButtonStatusFromAction();


};

#endif // ACTIONBUTTON_H

Класс * * +1011

#include "actionbutton.h"

ActionButton::ActionButton(QWidget *parent) :
    QPushButton(parent)
{
    actionOwner = NULL;
}

void ActionButton::setAction(QAction *action)
{

    // if I've got already an action associated to the button
    // remove all connections

    if( actionOwner != NULL && actionOwner != action ){
        disconnect( actionOwner,
                    SIGNAL(changed()),
                    this,
                    SLOT(updateButtonStatusFromAction()) );

        disconnect( this,
                    SIGNAL(clicked()),
                    actionOwner,
                    SLOT(trigger()) );
    }


    // store the action
    actionOwner = action;

    // configure the button
    updateButtonStatusFromAction();



    // connect the action and the button
    // so that when the action is changed the
    // button is changed too!
    connect( action,
             SIGNAL(changed()),
             this,
             SLOT(updateButtonStatusFromAction()));

    // connect the button to the slot that forwards the
    // signal to the action
    connect( this,
             SIGNAL(clicked()),
             actionOwner,
             SLOT(trigger()) );
}

void ActionButton::updateButtonStatusFromAction()
{
    setText( actionOwner->text() );
    setStatusTip( actionOwner->statusTip() );
    setToolTip( actionOwner->toolTip() );
    setIcon( actionOwner->icon() );
    setEnabled( actionOwner->isEnabled() );
    setCheckable( actionOwner->isCheckable() );
    setChecked( actionOwner->isChecked());

}
0 голосов
/ 03 мая 2018

В Qt Designer вы можете добавлять соединения вручную.Я думаю, что вы можете использовать обычный PushButton и подключить сигнал кнопки clicked() к слоту trigger() действия.

Допустим, есть pushButton_AddFile и actionAddFile.Вы можете добавить соединение в Signal/Slot Editor из Qt Designer следующим образом:

enter image description here

0 голосов
/ 17 ноября 2010

Я думаю, вам нужно реализовать какое-то конкретное действие. Посмотрите, есть ли в QtDesigner какой-то определенный Mime-Type для его компонентов. Все, что является перетаскиванием, должно быть реализовано таким образом. Конечно, это не так просто понять;)

...