Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

if you don't know how to use model/view/controller pattern, I'd recommend you to use QListWidget instead of QListView. Adding to QListWidget is way to simplier. You should create a slot where goes the signal from add button click, and a slot for delete button click.

Code for first slot:

m_pListWidget->addItem( m_pTextEdit->toPlainText() );

Code for second slot:

if ( QListWidgetItem* plwiCurrent = m_pListWidget->currentItem() )
{
    m_pListWidget->takeItem( m_pListWidget->row( plwiCurrent ) );
    delete plwiCurrent;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top