Karim M. El Tel
Karim M. El Tel

Reputation: 438

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

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

Upvotes: 2

Views: 4743

Answers (3)

Flarex
Flarex

Reputation: 531

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.

Upvotes: 1

O.C.
O.C.

Reputation: 6819

Something as below :

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

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

Upvotes: 4

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12195

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

Upvotes: 0

Related Questions