Frage

I have a QLineEdit, 2 QPushButtons (Add & Remove Buttons) and a QListView. I want to add the QLineEdit text to the QListView when the add button is clicked. Same way, I have to delete an item from the QListView if the remove button is clicked. I'm using a QStringListModel to add the QLineEdit text to the QListView. But I don't know how to delete the QListView item. How can I do this? Plz Help.. Thanks in Advance.

#ifndef  EXAMPLE_H
#define  EXAMPLE_H
#include <QWidget>
#include <QStringList>
#include <QStringListModel>


class EXAMPLE : public QWidget
{
    Q_OBJECT

 public:
     explicit EXAMPLE(QWidget *parent = 0);
     ~EXAMPLE();

 private slots:
      void on_addButton_released();
      void on_removeButon_released();

 private:
      Ui::EXAMPLE *ui;
      QStringList  stringList;
 };

 #endif // EXAMPLE_H


    EXAMPLE.CPP

    #include "EXAMPLE.h"
    #include <QStringListModel>


    EXAMPLE::EXAMPLE(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::EXAMPLE)
    {
        ui->setupUi(this);
        ui->listView->setModel(new QStringListModel(stringList));
    }

    EXAMPLE::~EXAMPLE()
    {
        delete ui;
    }

    void EXAMPLE::on_addButton_released()
    {
        stringList.append(ui->lineEdit->text());
        ((QStringListModel*) ui->listView->model())->setStringList(stringList);
        ui->lineEdit->clear();
    }

    void EXAMPLE::on_removeButon_released()
    {

    }
War es hilfreich?

Lösung

If your list view is only using single selection, the following will work:

void EXAMPLE::on_removeButton_released()
{
   QModelIndexList selected = ui->listView->selectionModel()->selectedIndexes();
   if (!selected.isEmpty())
   {
      stringList.removeAt(selected.first().row()-i);
      ((QStringListModel*) ui->listView->model())->setStringList(stringList);
   }
}

If your list view allows for multiple items to be selected, then you'll need something slightly more complex:

void EXAMPLE::on_removeButton_released()
{
   QModelIndexList selected = ui->listView->selectionModel()->selectedIndexes();
   if (!selected.isEmpty())
   {
      qSort(selected);
      for (int i=0; i<selected.count(); ++i)
      {
         stringList.removeAt(selected.at(i).row()-i);
      }
      ((QStringListModel*) ui->listView->model())->setStringList(stringList);
   }
}

There is also a means of removing the items directly from the item model (as opposed to removing it from the string list and then setting the string list on the model). Refer to the documentation for QAbstractItemModel::removeRow. If you go down this road, your method of adding items will also need to change.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top