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

╄→尐↘猪︶ㄣ 提交于 2019-12-02 01:35:43

Something as below :

connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(itemClickedSlot(QListWidgetItem *)));

void Form::itemClickedSlot (QListWidgetItem * itemClicked)
{
//Do something with clicked item
}

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!