PDA

View Full Version : Associating a string with a QListWidgetItem



dohzer
28th November 2010, 14:35
I want to write a simple program to let users create a list of notes.
I've got a QListWidget and a QPlainTextEdit and a button to allow new list items to be added.
Whenever a new item is added, I want to store the 'plain text' associated with the previous item.

Is there as simple way to link a QString pointer to a given QListWidgetItem? Or do I need to create another 'list' (say, an array of QString pointers) and match it to the QListWidget rows (the first item in my array would implicitly be the QString for the first QListWidge row)?

tbscope
28th November 2010, 14:41
Why QString pointers?

Take a look at:
http://doc.qt.nokia.com/4.7/qlistwidgetitem.html#setData

dohzer
28th November 2010, 14:48
Or just QStrings. Either way. I was thinking pointers because I might need to change the string, but I guess I can just clear() and append() to the QString.
I had a look at setData(), but I'm having trouble with the code.

Basically I defined a role as:
#define USER_ROLE_TEXT 1001;

and then tried to pass and retrieve my string, but I was getting some strange errors. Could you provide an example code line of reading and writing a string to the list item?

tbscope
28th November 2010, 15:06
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QListWidgetItem>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
explicit Widget(QWidget *parent = 0);
~Widget();

public slots:
void showNote(QListWidgetItem*);

private:
Ui::Widget *ui;
};

#endif // WIDGET_H




#include "widget.h"
#include "ui_widget.h"

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

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

QListWidgetItem *item = new QListWidgetItem;
item->setText("Item 1");
item->setData(1001, QString("This is the note that belongs to item 1"));
ui->listWidget->addItem(item);

item = new QListWidgetItem;
item->setText("Item 2");
item->setData(1001, QString("Another note. One that belongs to item 2"));
ui->listWidget->addItem(item);
}

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

void Widget::showNote(QListWidgetItem *item)
{
ui->plainTextEdit->setPlainText(item->data(1001).toString());
}


plainTextEdit and listWidget are added via designer.