Detecting if an item is clicked at at some row in a QlistWidget

前端 未结 3 839
误落风尘
误落风尘 2021-01-22 04:43

I Have been given this simple task ,

I have this list where i instert items whenever ok is clicked,void Form::ok() handle that event is supposed to add new list items t

相关标签:
3条回答
  • 2021-01-22 04:46

    You need to connect the itemClicked(QListWidgetItem * item) signal to some slot to handle clicks on an item.

    0 讨论(0)
  • 2021-01-22 04:47

    Something as below :

    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(itemClickedSlot(QListWidgetItem *)));
    
    void Form::itemClickedSlot (QListWidgetItem * itemClicked)
    {
    //Do something with clicked item
    }
    
    0 讨论(0)
  • 2021-01-22 04:50

    The QListWidgetItem stores its text as a QString so you may need to cast it to something else if you want to manipulate it. The QListWidgetItem itself holds no information about it's position, but QListWidget does.

    If you look at the documentation for QListWidget under signals you can see that there are a couple different states that you can execute a function during. I personally use currentItemChanged.

    http://qt-project.org/doc/qt-4.8/QListWidget.html#signals

    Update your constructor to include connecting your listWidget to myFunc:

    Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form) {
    ui->setupUi(this);
    connect(ui->listWidget, 
        SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this,
        SLOT(myFunc(QListWidgetItem *)));
    }
    

    And add this function to your class:

    void Form::myFunc(QListWidget *item) {
        int currentRow = ui->listWidget->currentRow();
        std::cout << (item->text()).toStdString() << std::endl;
    }
    

    That should get you the current position of the QListWidgetItem in the list and its text. Using item-> you can then change it's text and change some other things:

    http://qt-project.org/doc/qt-4.8/qlistwidgetitem.html

    Happy coding.

    0 讨论(0)
提交回复
热议问题