[Qt-interest] Binding a value to a slot

Reece Dunn msclrhd at googlemail.com
Thu May 20 10:19:19 CEST 2010


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