user2094257
user2094257

Reputation: 1715

Deleting a single item from a QListview with QStringListModel as model

I have a QListview which i'm using to display book titles using a QStringListModel as model. How can I delete the currently selected item? I wanto to only be able to delete one book title which should be the currently selected title. I read through a few similar questions but didn't find a clear answer anywhere. I tried using a QModelIndexList declared in my deleteBookButtonClicked slot but keep getting a variable undeclared error...

Upvotes: 2

Views: 1481

Answers (2)

Dean P
Dean P

Reputation: 2225

To get the currently selected index in a view object called "myQViewObject", simply type:

myQViewObject -> currentIndex()

Upvotes: 0

ramtheconqueror
ramtheconqueror

Reputation: 1964

// stringlistmodel.h

class StringListModel : public QStringListModel
{

public:

    explicit StringListModel(QObject* prnt=0);

    void deleteItem(const QModelIndex& index);
};

// srtringlistmodel.cpp
void StringListModel::deleteItem(const QModelIndex& index)
{
    if (!index.isValid() || index.row() >= stringList().size())
        return;
    removeRows(index.row(), 1);
}

use this like

StringListModel* model = new StringListModel(this);
model->setStringList(QStringList() << "Book 1" << "Book 2" << "Book 3");
ui->listView->setModel(model);
// C++11 style connect
connect(ui->pushButton, &QPushButton::clicked, [model, this]() {
    model->deleteItem(ui->listView->currentIndex());
});

Upvotes: 2

Related Questions