add icons to QAbstractModel for display in QListView



  • Hi,

    I want to add multiple icons to a text entry in my QAbstractModel but I'm unsure how, I can add one icon easily with:

    QAbstractItemModel *model = ui->HostList->model();
    QModelIndex idx = model->index(0,0);
         if (idx.isValid()) {
             model->setData(idx,QIcon("ping.png"),Qt::DecorationRole);
         }
    

    but

         QAbstractItemModel *model = ui->HostList->model();
         model->insertColumn(1);
         QModelIndex idx = model->index(0,1);
         if (idx.isValid()) {
             model->setData(idx,QIcon("ping.png"),Qt::DecorationRole);
         } else
             qDebug()<< "invalid index!";
    

    won't work. I'd expect the icon to show up on and then to be able to add as many additinal icons as columns got added by adjusting index() accordingly. What am I doing wrong here?


  • Lifetime Qt Champion

    Hi,

    The path to your icon file is relative so unless you copied the image files in the same folder as the application, it won't find it. Note that you can make use of Qt's resource system if you'd like to embed the icons within your application executable.



  • @SGaist said in add icons to QAbstractModel for display in QListView:

    Hi,

    The path to your icon file is relative so unless you copied the image files in the same folder as the application, it won't find it. Note that you can make use of Qt's resource system if you'd like to embed the icons within your application executable.

    Great, that was what I was looking for, so I've added the images now from: menu --> File --> New File or Project --> under Files and Classes panel, choose Qt --> On your ride window select "Qt resource file"
    it compiles fine but it seems like I still need to files in the directory too. How do I change the path to load the file from the resources instead of from the file system?


  • Lifetime Qt Champion

    Since you've put it in Qt's resource system, you have to update the path and use the :/ prefix.



  • @SGaist said in add icons to QAbstractModel for display in QListView:

    Since you've put it in Qt's resource system, you have to update the path and use the :/ prefix.

    Excellent! Just had to adjust the resource prefix to /, too! Great! Thanks!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.