简体   繁体   English

如何从QPushButton恢复项目?

[英]How to recover item from a QPushButton?

I made a code in c ++ with the Qt framework. 我使用Qt框架在c ++中编写了代码。 The goal is to add lines that contain a QLabel "url", a QLineEdit "name" and QPushButton "remove". 目标是添加包含QLabel“ URL”,QLineEdit“ name”和QPushButton“ remove”的行。 I add the line with a QPushButton named "Add". 我用名为“添加”的QPushButton添加该行。

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. 我用QSignalMapper尝试了一种方法,但是它不起作用。 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 可以使用lambda函数连接QPushButton的clicked信号

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)); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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