Add a delete Button to each Item in QListView

℡╲_俬逩灬. 提交于 2019-12-10 17:18:48

问题


Is it somehow possible to add to each Item in a QListview a Button which is deleting the Object onClick? As shown in the following Picture:

EDIT: As I'm new in QT it would be nice to have some example, to understand it better. And as it seems there are three different Ways? What will be the best? Do use a QAbstractItemView?


回答1:


Yes. You'll need to use:

QAbstractItemView::setIndexWidget ( const QModelIndex & index, QWidget * widget )

QListView inherits QAbstractItemView and when you're trying to customize list/tree views that's usually the place to look. Be careful though, without a delegate this doesn't scale very well. Check out this thread: http://www.qtcentre.org/threads/26916-inserting-custom-Widget-to-listview




回答2:


You can also go for a generic approach that can work on variety of containers, including the underlying model of your list view.

Each item in the list has a requestRemoval(Item*) signal and a removeMe() slot, connect the X button to the removeMe() slot in each item constructor, in removeMe() you emit the requestRemoval(this) signal, which is connected to a removeHandler(Item*) slot in your "parent" object upon creation of that item, which receives the pointer of the item which has requests deletion, and removes it from the underlying container being used.

Basically, pressing the remove button causes that particular item to send a pointer of itself to the parent's remove handler which removes that entry.

EDIT: Note that this is a generic approach, as noted in the comments below it can be applied without signals and slots as well, and even though it will work it is not the most efficient solution in your particular case.



来源:https://stackoverflow.com/questions/25933326/add-a-delete-button-to-each-item-in-qlistview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!