简体   繁体   中英

How to add a QString to a QListView using a QLineEdit

I want to use a QLineEdit to write a QString, then using a QPushButton, I want to add an item (a string) to a listView

Here is what I got:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);

    model = new QStringListModel(this);

    QStringList list;

    list << "Some Item";

    model->setStringList(list);

    ui->listView->setModel(model);
    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void MainWindow::on_pushButton_3_clicked()
{
    //add
    int row = model->rowCount();   // model = new QStringListModel
    model->insertRow(row);

    QModelIndex index = model->index(row);
    ui->listView->setCurrentIndex(index);
    ui->listView->edit(index);  // instead of edit, I'd like to ... add a QString
}

Problem is I don't want to be able to edit (this was all I was manage to do by myself). I want now to instead add an item at CurrentIndex, and that item to be the text field of lineEdit . How do I get access to that field? is it lineEdit->text() ? and how do I add that to the list view?

I simply do not know how to add anything to a list. I found edit by mistake, and google has not helped so far. I'm hoping Stack Overflow can, and will.

EDIT: I have decided to try this, but it doesn't seem to be the best solution

void MainWindow::on_pushButton_3_clicked()
{
    //add

    QStringList list;
    list = model->stringList();
    list.append(ui->lineEdit->text());
    model->setStringList(list);
}

But this seems to be an odd way of doing things. Also it seems to include a newline for some reason.

There is already an example of how to use a QStringListModel here: https://stackoverflow.com/a/5825113/496445

model->insertRow(model->rowCount());
QModelIndex index = model->index(model->rowCount()-1)
model->setData(index, str);

Note that in this suggested approach, you do not need the QStringList, unless you already had one for another reason and want to initialize with it.

When you use a Q*View instead of a Widget, you will be dealing with the model directly for data instead of the view. The view will be notified when the model changes. In this case, you would probably be accessing your lineEdit like this:

QString str = ui->lineEdit->text();

Another way; right-click to listView and select "morph into" -> "QListWidget"

At this time you can see this function "lst-> addItem ("str");"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM