【问题标题】:Qt: How to draw (and use) lineEdit inside delegate?Qt:如何在委托内绘制(和使用)lineEdit?
【发布时间】:2022-06-10 23:59:29
【问题描述】:

我有一个自定义列表,在视图上(使用QStyledItemDelegate)我想显示很多东西,包括文本编辑 (考虑一个在线购物车,您可以在其中拥有商品(照片和信息),在它们旁边您可以更改数量,但在文本编辑中,而不是在旋转框中)。

此文本编辑应该能够与模型通信。目前我只能画一个空的textEdit,但我不知道如何正确连接到editorEvent(和createEditorsetEditorData)。

void CustomDelegate::paint(QPainter *painter,
                           const QStyleOptionViewItem &opt,
                           const QModelIndex &idx) const
{
      // My other painting stuff (labels, shapes...)
    QStyleOptionFrame panelFrame;
    QLineEdit lineEdit;
    panelFrame.initFrom(&lineEdit);
    panelFrame.rect = rectLE;
    panelFrame.state |= QStyle::State_Sunken;
    QApplication::style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panelFrame, painter);
}

QWidget *CustomDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto editor = new QLineEdit(parent);
    editor->setText("test");
    return editor;
}


void CustomDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    auto lineEdit = dynamic_cast<QLineEdit*>(editor);
    if(lineEdit)
    {
        lineEdit->setText("test2");
    }
}

因此,我只能看到一个空的lineEdit 并且无法真正与之交互。

  • 如果我在一个 modelIndex 代表中包含多个 lineEdits,我如何在 setEditorDatacreateEditor 中区分它们?

谢谢

【问题讨论】:

    标签: c++ qt delegates qpainter qlineedit


    【解决方案1】:

    默认情况下,QAbstractItemView 中的编辑器仅由设置为它的编辑触发器创建。参考docs

    要使视图在渲染行作为常规小部件的意义上具有交互性,您可以使用一种解决方法。

    我已将这种方法用于QListViewQStyledItemDelegate

    当我遇到同样的问题时,我跟踪了 viewport 的鼠标移动事件,以在鼠标光标下获取 QModelIndex,如果它有效且与之前的值不同,我关闭编辑器 (如果已打开一个)并使用方法 QAbstractItemView::closePersistentEditorQAbstractItemView::openPersistentEditor 打开一个新的。

    在我的QStyledItemDelegate 派生类中,我覆盖了createEditorsetEditorDataupdateEditorGeometry 方法。

    createEditor 中只需创建一个小部件,在updateEditorGeometry 中将Geometry 设置为编辑器,在setEditorData 中从QModelIndex 中获取渲染所需的数据并将其设置为编辑器小部件。

    我用来在paint 方法中呈现所有行的小部件类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      相关资源
      最近更新 更多