【问题标题】:QListView and delegate display unintended itemQListView 和委托显示意外项
【发布时间】:2013-02-14 19:35:17
【问题描述】:

我的 QListView 有问题,它在 QListView 的左上角绘制了一个意外项目:

http://s4.postimage.org/64orbk5kd/Screen_Shot_2013_02_14_at_20_23_14.png

我在 QListView 中使用 QStyledItemDelegate :

m_stringList.push_back("FIRST");
m_stringList.push_back("SECOND");
m_stringList.push_back("THIRD");
m_model.setStringList(m_stringList);

ui->processesListView->setFlow(QListView::LeftToRight);
ui->processesListView->setModel(&m_model);
ui->processesListView->setItemDelegate(new ProcessItemDelegate(this, ui->processesListView));

委托(ProcessItemDelegate)paint方法使用自定义的QWidget来显示信息:

void ProcessItemDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex &inIndex ) const
{
  _listItem->setContent(_listView->model()->data(inIndex).toString());
  painter->save();
  painter->translate(option.rect.center());
  _listItem->render(painter);
  painter->restore();
}

QWidget的setContent方法很简单:

void ProcessItem::setContent(const QString &s)
{
  ui->processId->setText(s);
}

【问题讨论】:

    标签: qt listview


    【解决方案1】:

    我还有另一种方法可以使用 QListWidget 将小部件添加到某个列表。

    例如知道ui->historyViewQListWidget 元素和HistoryElementViewQWidget 的子类。

    void View::onHistoryChanged(const QList<HistoryElement> &history)
    {
        clearHistory();
        foreach(HistoryElement elt, history)
        {
            HistoryElementView *historyViewElement = new HistoryElementView(elt.getDateTime("dd/MM/yyyy - hh:mm"), elt.getFilename());
            QListWidgetItem *item = new QListWidgetItem();
    
            ui->historyView->addItem(item);
            ui->historyView->setItemWidget(item, historyViewElement);
        }
    }
    
    void View::clearHistory()
    {
        QListWidgetItem *item;
    
        while (ui->historyView->count() != 0)
        {
             item = ui->historyView->takeItem(0);
    
            delete item;
        }
    }
    

    您不需要删除QListWidgetItem 中的小部件,它将由 Qt 处理。

    一旦您的小部件在列表中,您可以使用以下方法检索它们:

    // Using index
    QListWidgetItem *item = ui->historyView->item(0);
    HistoryElementView *elt = qobject_cast<HistoryElementView *>(ui->historyView->itemWidget(item));
    
    // Using position
    QListWidgetItem *item = ui->historyView->itemAt(pos);
    HistoryElementView *historyElement = qobject_cast<HistoryElementView *>(ui->historyView->itemWidget(item));
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2016-07-18
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多