简体   繁体   中英

How to recover item from a QPushButton?

I made a code in c ++ with the Qt framework. The goal is to add lines that contain a QLabel "url", a QLineEdit "name" and QPushButton "remove". I add the line with a QPushButton named "Add".

The part to add the line works. The code is the following :

name=new QLineEdit("",list);
url=new QLabel("",list);
removeLine=new QPushButton("remove",list);
//list is a QListWidget
hbox=new QHBoxLayout;
hbox->addWidget(name);
hbox->addWidget(url);
hbox->addWidget(removeLine);

widget = new QWidget;
widget->setLayout(hbox);
item=new QListWidgetItem;
item->setSizeHint(QSize(0,50));
list->addItem(item);
list->setItemWidget(item,widget);

When I press the remove button, I would like the corresponding line to be deleted. The problem is that I can not find the item of each remove button.

I tried a method with QSignalMapper but it does not work. Here is the code:

i = list->currentRow();
signalMappper=new QSignalMapper(this);
connect(signalMappper,SIGNAL(mapped(int)),this,SLOT(removeLineEditLabelAndButton(int)));
connect(removeLine,SIGNAL(clicked()),signalMappper,SLOT(map()));
signalMappper->setMapping(removeLine,i);

//SLOT
void PanoramaWidget::removeLineEditLabelAndButton(int row){
 item= list->takeItem(row);
 list->removeItemWidget(item);
 delete item;
}

How would you solve this problem?

Can use lambda function to connect clicked signal of QPushButton

list = new QListWidget(this);

QLineEdit * name = new QLineEdit("", list);
QLabel * url = new QLabel("", list);
QPushButton * removeLine = new QPushButton("remove", list);
//list is a QListWidget
QHBoxLayout * hbox = new QHBoxLayout;
hbox->addWidget(name);
hbox->addWidget(url);
hbox->addWidget(removeLine);

auto widget = new QWidget;
widget->setLayout(hbox);
auto item = new QListWidgetItem;
item->setSizeHint(QSize(0, 50));
list->addItem(item);
list->setItemWidget(item, widget);

connect(removeLine, &QPushButton::clicked,
    [this, item]() {list->takeItem(list->row(item)); });

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