向QListWidget的现有项添加文本

Adding text to existing item of QListWidget

本文关键字:添加 文本 QListWidget      更新时间:2023-10-16

所以我想给我的QListWidget列表添加一个额外的文本,代码如下:

for (int i = 0; i < ui->history->count(); i++ )
{
    ui->history->item(i)->text().append(QTime::currentTime().toString());
}

这行不通。

我已经 qDebug标记了所有列表项的代码:

qDebug() << "item(" << i << ")->text() : " << ui->history->item(i)->text();

之后,我收到了这样的输出:

item( 0 )->text() :  "http://www.google.ru/?gfe_rd=cr&ei=cT6wV9PDKI-8zAXjlaCIDw"
item( 1 )->text() :  "https://news.google.ru/nwshp?hl=ru&tab=wn"  
item( 2 )->text() :  "https://news.google.ru/news?pz=1&hl=ru&tab=nn"
item( 3 )->text() :  "https://news.google.ru/news?pz=1&hl=ru&tab=nn"

显然这个函数输出item的所有文本,那么为什么我不能在那里附加任何其他字符串呢?

隐式共享确保文本不会被直接更改。您必须显式地设置文本值:

QString txt = ui->history->item(i)->text().append(QTime::currentTime().toString());
ui->history->item(i)->setText (txt);

text()按值返回文本,而不是按引用返回。您需要使用setText来修改文本