Removing item from QListWidget from inside a Widget

1.4k views Asked by At

I have a QListWidget in my MainWindow that displays a list of VideoWidgets (a custom QWidget). VideoWidget has a clickable label where on clicking the label it should delete a file and then remove the QListItem which holds the VideoWidget from the QListWidget. Here is my VideoWidget class:

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent)
{
    ClickableLabel *smallRed = new ClickableLabel(this)
    //...
    QObject::connect(smallRed,SIGNAL(clicked()),this,SLOT(removeVideo()));
}
void VideoWidget::removeVideo(){
    //...code to remove a file
    QListWidget* list = myParent->getList();        
    QListWidgetItem* item = list->takeItem(list->currentIndex().row());
    myList->removeItemWidget(item);
}

The problem is that clicking the smallRed label will not select its item in the QListWidget which means that list->currentIndex().row() will return -1. Clicking anywhere else in the Widget does select the current item. For the code to work I currently have to first click anywhere in the VideoWidget and then click its ClickableLabel. Is there any way I can achieve the same effect with one single click on my ClickableLabel?

1

There are 1 answers

10
Jablonski On

From your previous qestion, we suggested use signal and slots. For example:

for(int r=0;r<3;r++)
{
    QListWidgetItem* lwi = new QListWidgetItem;
    ui->listWidget->addItem(lwi);
    QCheckBox *check = new QCheckBox(QString("checkBox%1").arg(r));
    check->setObjectName("filepath");
    connect(check,SIGNAL(clicked()),this,SLOT(echo()));
    ui->listWidget->setItemWidget(lwi,check);
}

Slot:

void MainWindow::echo()
{
    qDebug() << sender()->objectName() << "should be remmoved";
}

It is not unique way to solve this problem, but it shows all main things, with signals and slots mechanism, objectName and sender() you can achieve all what you need.

sender() return object which send signal, you can cast it, but if you need only objectName you should not cast.