[Qt-interest] Overwriting public slots and qobject_cast

Rohan McGovern rohan.mcgovern at nokia.com
Thu Jun 4 00:21:35 CEST 2009


On Thursday 04 June 2009, ext Álvaro Morais wrote:
> Hi.
>
> I want to make a custom progressBar that changes color with
> percentage. For example 25% will give a highlight red, 50%
> Yellow, etc...
>
> It will also automatically give the password entropy of a
> QString, so the setValue SLOT will become private, since there is
> no need to change it from outside.
>
> I'm using the promote to custom widget on the QtDesigner.
>
> My question is: What is the best way of overwriting the public
> slots?
>
> is it safe to do this:
>
> class PasswordQuality : public QProgressBar
> {
> ...
> private slots:
>     virtual void setValue ( int value ) {
> 	qobject_cast<QProgressBar*>(this)->setValue(value);
>
> 	... //code to change the palette.
> 	}
> };
>

You _can't_ override QProgressBar::setValue in general, because it's 
not marked as virtual.  Marking it as virtual in your subclass 
doesn't help.

You _can_ override it for the specific case of metacalls - if you 
implement a slot with the same name in a subclass, as you have 
above, then that slot will be called whenever "setValue" is invoked 
by a signal-slot connection, QMetaObject::invokeMethod, and 
similar.

However I wouldn't recommend it, it will make your code more 
difficult to understand.

> Am I using qobjet_cast the right way?

There's no need to use it here, just: QProgressBar::setValue(value);

Suggest you give up on trying to override setValue and simply 
connect to the valueChanged signal instead.

-- 
Rohan McGovern
Qt Software, Nokia




More information about the Qt-interest-old mailing list