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

醉酒当歌 提交于 2019-12-04 04:45:29

问题


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 to the list.

Now what am not able to do is to detect the if an item is clicked at at some row then do something according to that, this is my code..

#include "form1.h"
#include "form.h"
#include "ui_form.h"
#include "ui_form1.h"
#include<QScrollArea>
#include<QScrollBar>

//#include <QgeoPositioninfo.h>

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);

}
Form::~Form()
{
    delete ui;
}

void Form::ok()
{
    QIcon  mypix  (":/karim/test.png");

    QListWidgetItem* newItem = new QListWidgetItem;
    newItem->setText("pixmix");
    newItem->setIcon(mypix);

    int row = ui->listWidget->row(ui->listWidget->currentItem());
    this->ui->listWidget->insertItem(row, newItem);

    //if(item at row x is clicked)
     {
     //do something
     }
}

Please be specific in yout answer i will appreciate that


回答1:


Something as below :

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

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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/7008611/detecting-if-an-item-is-clicked-at-at-some-row-in-a-qlistwidget

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