how to get a widget from QListWidgetItem

2019-02-24 21:08发布

问题:

I made a QListWidget. In QLisitWidgetItems, i added a QVBoxLayout. That QVBoxLayout contain three QLabels. How to get the values inside QLabel while click QListWidgetItem

//creating list view items(three QLabels)

Lblnames::Lblnames(QString strid,QString strname,QString strmob,QWidget *parent)
        : QWidget(parent)
    {
        QLabel *lblid=new QLabel(strid);
        QLabel *lblname=new QLabel(strname);
        QLabel *lblnumber=new QLabel(strmob);

        lblid->setFont(QFont("Times", 1));
        lblname->setFont(QFont("Times", 12, QFont::Bold));

        lblid->hide();

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(lblid);
    layout->addWidget(lblname);
    layout->addWidget(lblnumber);
    setLayout(layout);
}

//creating list

listWidget=new QListWidget();
    for(int i=0;qry.next();i++)
    {
        qDebug()<<QString("%1").arg( qry.value(1).toString());
        Lblnames *lblnames = new Lblnames(QString("%1").arg( qry.value(0).toString()),QString("%1").arg( qry.value(1).toString()),QString("%1").arg( qry.value(2).toString()));
        item = new QListWidgetItem();
        item->setSizeHint(QSize(0,60));
        item->setFont(QFont("Arial", 1));
        listWidget->addItem(item);
        listWidget->setItemWidget(item,lblnames);

        }

回答1:

first you need to add methods to LblNames to fetch the label text.Then Declare the 3 Qlabels as member variables of LblNames class.

QString LblNames::getLabelId()
{
    return lblid->text();
}


QListItemWidget* item = listWidget->itemAt(index);
LblNames widget = <dynamic_cast>(LblNames*)( listWidget->itemWidget(item) );
widget->getLabelId();/*Add these to LblNames class first*/
widget->getLabelText();

You should use google for such things . dynamic_cast is used to cast from a super class to one of its subclasses.



标签: qt4