[Qt-interest] Encapsulates question.
Andre Somers
andre at familiesomers.nl
Thu Aug 12 14:57:08 CEST 2010
Hi,
Op Do, 12 augustus, 2010 2:44 pm, schreef phil prentice:
> Hi
> I would like to clarify how I should do something using QT.
>
> I have a class that encapsulates an array of custom objects i.e.
>
> class Fred
> {
> ...
> private:
> Mike mike[6]; // Custom widgets.
> void func1(int index);
> }
> I want to catch mouse events in mike and call a private function in
> Fred.
> So I assume that I should use a signal to interface between mike and
> fred.
>
> i.e.
> void Mike::mousePressEvent(QMouseEvent *event)
> {
> // Setup widgets for the trace adjustment group (uses current net).
> emit testSelected(index);
> }
>
> Correct so far?
Yes, though I would not use a plain array of (pointers to?) widgets. Use
Qt's container classes instead, like QVector<QWidget*>.
> Now the index I wish to pass back is to identify which widget was
> selected.
> How best to do this?
> Should I use objectName() to identify the object in mousePressEvent or is
> there a better way? Or should I pass the this pointer and let Fred find it
> by
> searching the array list?
Simple option: add a pointer to to the Mike object to the signal, thus doing
emit testSelected(index, this);
Alternatively, you can use QSignalMapper from your Fred object, and set up
a mapping between a Mike object and some key that makes sense to you (such
as the index of that Mike in the QVector or array). Problem with that is
that QSignalMapper works best with signals that don't have arguments at
all.
Finally, you can look into QObject::sender(). It returns the sender of the
signal (if any!) as a QObject* pointer. I don't find it a pretty solution,
but it should work. A simple cast to a Mike pointer and you should be
done:
Fred::selected(index) {
Mike* theMike = qobject_cast<Mike*>(sender());
if (!theMike) {
//code was triggered by something else than Mike sending a signal.
} else {
// Mike is cool!
}
}
André
More information about the Qt-interest-old
mailing list