Understanding subclassing

Hello there :)
I'm using the QtCreator IDE to build my project but it will not be a problem helping me out.

Let's say that there is a class called QListWidget. An object of this class can accept items like this:

listwidget->addItem(QListWidgetItem *item)

QListWidgetItem is another class. Every QListWidgetItem object has functions such as setToolTip() and setStatusTip(), but I also want to store there another string, not visible by the user.

So, I thought that subclassing QListWidgetItem was a good idea, and I implemented it as simply as I could:

1
2
3
4
5
class MyListItem : public QListWidgetItem
{
public:
    QString image_path;
};


Then, I used the following code:
1
2
3
4
MyListItem * item = new MyListItem();
item->setText("This is a new item inside a listwidget and this is visible to the user text");
item->image_path="This is text not visible to the user, I store it as a public variable";
ui->listWidget->addItem(item);


I don't feel I've won something like this, though. Once my 'item' is stored inside the listWidget, I cannot recall the image_path function. The QListWidget class has a function:

ui->listWidget->item(int position) that returns a specific QListWidgetItem. But it is not a MyListItem, thus I cannot call the 'image_path' variable to see its value.

I am obviously missing somethinig. How can what I ask for be implemented?

I know that I ask a question depending on classes of a specific IDE, but I think that the question can be generalized. When a Class accepts specific items, and you subclass the class of these items in order to store more data in them, how can you recall these data while the first class returns the normal class of the items you have subclass and not your own class?
Last edited on
You can't access something (image_path) when it's not there.

In other words, if the list item was created by li = new QListWidgetItem, it won't be an item of your subclass. However, you can test a list item to determine if it is an instance of your subclass by using a dynamic_cast.
1
2
3
4
5
6
7
8
9
10
 
QListWidgetItem * li;
MyListItem * myitem;
int pos = 0;

li = ui->listWidget->item(pos);
myitem = dynamic_cast<MyListItem *> (li);
if (myitem != NULL) 
{  // do something with image_path
}






So, what dynamic_cast will do is to give me back the image_path variable so as to use it?
The dynamic_cast will give you a pointer to MyListItem if li was created from MyListItem, or NULL if li was created from only QListWidgetItem.

Once you know you have a valid pointer to a MyListItem instance, you can access image_path.
Epic!
Thanks :)
Topic archived. No new replies allowed.