PDA

View Full Version : How to pass a Qwidget to a function into a children class ?



tonnot
8th February 2011, 18:21
I know that it is a recurrent theme, but I dont know to do this :
I want to pass two different widgets to a function into a class I have instantiated from main app.
The two different widgets can be Qlabel and /or QTextedit.

So, I'd want to have a function like this
Myfuntion(Qwidget a_widget) {
A_widget_to_remember=a_widget

.... }
Later in another function I want to do something with 'a_widget_to_remember'

if A_widget_to_remember=Qlabel ....
if A_widget_to_remember=QTextedit ....

1.- How I must to pass the label or Qtextedit to the function ?
Using pointers ? Can anyonbe give some easy code ?
2.- How can I identify what kind of Qwidget is 'A_widget_to_remember'

Thanks.

agarny
8th February 2011, 18:47
You clearly want to pass a pointer to your object, otherwise how can you keep track of it? Also, you might want to have a look at overloaded functions (http://www.cplusplus.com/doc/tutorial/functions2/#function_overload).
There are different possible approaches, depending exactly on what you want to do, how generic a solution you want it to be. The easiest would be to have two different variables in your class, one for QLabel and another for QTextEdit, and a flag that tells you which should be used.

ChrisW67
8th February 2011, 21:49
1.- How I must to pass the label or Qtextedit to the function ?
Using pointers ? Can anyone give some easy code ?

Pass the widgets by pointer. You cannot pass them by value, even if that made sense, because they do not have the requisite copy constructor.


class MyClass {
...
private:
QWidget *aWidget;
};

MyClass::record(QWidget *widget)
{
aWidget = widget;
}



2.- How can I identify what kind of Qwidget is 'A_widget_to_remember'

QObject qobject_cast to the relevant type and check the returned pointer.

tonnot
9th February 2011, 07:28
Thank you very much !