Associating a string with a QListWidgetItem
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)?
Re: Associating a string with a QListWidgetItem
Re: Associating a string with a QListWidgetItem
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?
Re: Associating a string with a QListWidgetItem
Code:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QListWidgetItem>
namespace Ui {
class Widget;
}
{
Q_OBJECT
public:
explicit Widget
(QWidget *parent
= 0);
~Widget();
public slots:
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
Code:
#include "widget.h"
#include "ui_widget.h"
ui(new Ui::Widget)
{
ui->setupUi(this);
item->setText("Item 1");
item
->setData
(1001,
QString("This is the note that belongs to item 1"));
ui->listWidget->addItem(item);
item->setText("Item 2");
item
->setData
(1001,
QString("Another note. One that belongs to item 2"));
ui->listWidget->addItem(item);
}
Widget::~Widget()
{
delete ui;
}
{
ui->plainTextEdit->setPlainText(item->data(1001).toString());
}
plainTextEdit and listWidget are added via designer.