[Qt-interest] How To: pass extra data to object slots from menu action signals?

KC Jones kc at asperasoft.com
Tue Feb 2 03:18:35 CET 2010


Deriving from QAction is the way to go.  Rather than describe it, here's my
code:

    class OpenPackageAction : public QAction {
        Q_OBJECT

    public:
        OpenPackageAction(QString package_id, QObject* parent) :
QAction(parent) {
            setData(package_uid);
            connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
        }

    signals:
        void openPackage(Package* p);

    protected slots:
        void onTriggered() {
            emit openPackage(data().toString());
        }
    };

Seems pretty lean and clean to me.

On Mon, Feb 1, 2010 at 2:06 PM, kent williams <nkwmailinglists at gmail.com>wrote:

> I found a way around this problem, but somehow it feels sneaky:
>
> 1. Derive a new class from QAction, and add the data I need to this class.
> 2. Add my derived-from-QAction class to the QMenu after setting the member
> data.
> 3. In the action connected to my action, cast sender() to my derived
> type, and retrieve the needed data from it.
>
> As elegant as the signal/slot paradigm is, I'd think there would be a
> more 'Qt' way of doing this.
>
> On Mon, Feb 1, 2010 at 3:35 PM, kent williams <nkwmailinglists at gmail.com>
> wrote:
> > I am working on a program that dynamically adds and removes actions
> > from menus, based on adding and deleting objects in the user
> > interface.
> >
> > This causes a problem in QT -- actions attached to a QMenu send a
> > triggered() signal, but that signal can only be connected to a slot in
> > my class with a similar signature, e.g. triggered() or triggered(bool
> > b).
> >
> > I figured out that I could use a QSignalMapper to map triggered() from
> > a menu action to a slot that takes a single string argument.  But what
> > I'd like to do is pass in two strings. In other words I have a
> > multilevel menu like this
> >
> > File
> >    Save
> >       Type1
> >           Object1
> >           Object2
> >       Type2
> >           Object1-1
> >           Object1-2
> >
> > And I want to trigger this slot
> >
> > void SaveSomething(Type, ObjectName);
> >
> > What I'm asking is this: is there a way to have a Signal send more
> > information to an object?
> >
> > The only thing I could figure out is to construct strings containing
> > both arguments, and then use QSignalMapper to map that Action to that
> > string.
> >
> > Is there a better way?
> >
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100201/d408d328/attachment.html 


More information about the Qt-interest-old mailing list