[Qt-interest] Binding a value to a slot

Tony Rietwyk tony.rietwyk at rightsoft.com.au
Thu May 20 16:44:56 CEST 2010


Have a look at QActionGroup.triggered, and just
setProperty("MY_ALIGN_VALUE", Qt::AlignXXX ) on each.  

Strangely, QButtonGroup has a better api, since it supports the extra int
when you add the buttons. 

Alternatively, you use the more general QSignalMapper. 

Tony.



> -----Original Message-----
> From: qt-interest-bounces at trolltech.com 
> [mailto:qt-interest-bounces at trolltech.com] On Behalf Of Reece Dunn
> Sent: Thursday, 20 May 2010 18:19
> To: QT Interest List
> Subject: [Qt-interest] Binding a value to a slot
> 
> 
> Hi,
> 
> If I have a signal that has a signature signal(), specifically for the
> QAction triggered(), I need a function (signal or slot) that has the
> same signature.
> 
> Now, this is fine for the most part, but leads to writing more code in
> some situations:
> 
> 1/ text alignment
> 
> I need to write:
> 
> class MainWindow : public QMainWindow {
>    QTextEdit *m_edit;
> public:
>    void alignLeft() { m_edit->setAlignment(Qt::Left); }
>    void alignRight() { m_edit->setAlignment(Qt::Right); }
>    void alignCenter() { m_edit->setAlignment(Qt::Center); }
>    void alignJustify() { m_edit->setAlignment(Qt::Justify); }
> };
> 
> and connect them up accordingly. What I want is something like:
> 
>    connect(alignLeftAction, SIGNAL(triggered()), m_edit,
> bind(QTextEdit::setAlignment, Qt::Left));
>    ...
> 
> 2/ find / replace
> 
> I have a find/replace dialog that has a setMode function to set it to
> a find or replace dialog. I have a find() slot and replace() slot that
> are bound to the corresponding QAction trigger() signal, where those
> two functions vary just by the mode option.
> 
> I could do:
> 
>    void findReplace(FindReplaceDialog::Mode mode) { ... }
>    void find() { findReplace(FindReplaceDialog::Find); }
>    void replace() { findReplace(FindReplaceDialog::Replace); }
> 
> and:
> 
>    connect(findAction, SIGNAL(triggered()), this, SLOT(find()));
>    connect(replaceAction, SIGNAL(triggered()), this, SLOT(replace()));
> 
> but the find and replace functions are effectively redundant. What I
> want to do is have:
> 
>    void findReplace(FindReplaceDialog::Mode mode) { ... }
> 
> and:
> 
>    connect(findAction, SIGNAL(triggered()), this,
> bind(MainWindow::findReplace, FindReplaceDialog::Find));
>    connect(replaceAction, SIGNAL(triggered()), this,
> bind(MainWindow::findReplace, FindReplaceDialog::Replace));
> 
> Is there a way to do this?
> 
> - Reece




More information about the Qt-interest-old mailing list