Search code examples
qtqtexteditqlistviewqt4.8qpushbutton

Qt- How to display the Text Edit String in a List View?


I have a QTextEdit , 2 QPushButtons (Add n Remove Buttons) and a QListView. When i am entering the text in the Text Edit and click the Add Button, the Text should be added in the List View. Then, if I select any one of the added text from the List View & Click the Remove Button, the Text should be removed from the ListView. I dont know how to achieve this. Plz Help me to solve this. Thanks in Advance.


Solution

  • Assuming you are using a QStandardItemModel and you have the following variables

    QPushButton* addButton;
    QPushButton* removeButton;
    QTextEdit* textEdit;
    QStandardItemModel* model;
    MyObject* this;
    

    the following code should do it:

    connect(addButton, SIGNAL(clicked()), this, SLOT(onAddButtonClicked()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(onRemoveButtonClicked()));
    

    Then the two slots in your class MyObject you define do the following:

    void MyObject::onAddButtonClicked() {
        model->appendRow(new QStandardItem(textEdit->plainText());
    }
    
    void MyObject::onRemoveButtonClicked() {
        if (model->rowCount() == 0)
            return;
        delete model->takeItem(model->rowCount() - 1);
    }
    

    Updating the view gets handled by QStandardItemModel