【问题标题】:QItemDelegate with custom widgets带有自定义小部件的 QItemDelegate
【发布时间】:2014-04-14 10:51:44
【问题描述】:

我的QTableViewQItemDelegate 课程有问题。对于一列,我的代表创建了一个简单的组合框,一切正常。对于我的第二列,我需要一个在一个小部件中包含两个组合框的小部件。

我在QItemDelegate 中编写了以下代码,为了清楚起见,这仅显示了我的第二列的代码,即不起作用的那一列。另一个简单的组合框没有显示,因为它工作正常:

QWidget *UserDefinedUnitsDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem & option ,const QModelIndex & index ) const
{
    //set up a simple widget with a layout
    QWidget* pWidget = new QWidget(parent);
    QHBoxLayout* hLayout = new QHBoxLayout(pWidget);
    pWidget->setLayout(hLayout);

    //add two combo boxes to the layout
    QComboBox* comboEditor = new QComboBox(pWidget);    
    QComboBox* comboEditor2 = new QComboBox(pWidget);   

    //now add both editors to this
    hLayout->addWidget(comboEditor);
    hLayout->addWidget(comboEditor2);
    return pWidget;
}

现在它显示得很好,但是当我编辑它并单击其他地方时,它不会停止编辑。有没有人可以指点一下?

编辑:所以我需要在某个时候调用 CommitData() 和 closeEditor()。谁能提供关于在哪里调用这些的指针?

谢谢。

【问题讨论】:

  • 您的问题与QItemDelegate 有什么关系?显示一些代码。
  • 已更新以显示此代码在 QItemDelegate::createEditor 方法中。谢谢指出,不是很清楚。
  • 你在哪里打电话QAbstractItemView::closeEditor / commitData
  • 我没有设置它,因为当我使用一个简单的 ComboBox 时,它似乎可以自己做。
  • 是的。但是您使用的是自定义编辑器。

标签: c++ qt qtableview qitemdelegate


【解决方案1】:

您可以将编辑器小部件保留为类的成员,并在其中一个组合框的当前索引发生更改时发出 commitData。因此,您可以将 currentIndexChanged(int) 连接到一个插槽并从那里发出 commitData:

QWidget *UserDefinedUnitsDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem & option ,const QModelIndex & index ) const
{
    //set up a simple widget with a layout
    pWidget = new QWidget(parent);
    QHBoxLayout* hLayout = new QHBoxLayout(pWidget);
    pWidget->setLayout(hLayout);

    //add two combo boxes to the layout
    QComboBox* comboEditor = new QComboBox(pWidget);    
    QComboBox* comboEditor2 = new QComboBox(pWidget);   

    connect(comboEditor,SIGNAL(currentIndexChanged(int)),this,SLOT(setData(int)));
    connect(comboEditor2,SIGNAL(currentIndexChanged(int)),this,SLOT(setData(int)));

    //now add both editors to this
    hLayout->addWidget(comboEditor);
    hLayout->addWidget(comboEditor2);
    return pWidget;
}

void UserDefinedUnitsDelegate::setData(int val)
{
    emit commitData(pWidget);
}

【讨论】:

  • 嗯,它可以工作,但理想情况下它不会设置数据,直到你完成(可能)编辑两个组合框。我能想到的就是检查视图中其他地方的点击。
猜你喜欢
  • 2016-01-26
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
相关资源
最近更新 更多