【问题标题】:QPushButtons in a column of a treeview树视图列中的 QPushButtons
【发布时间】:2016-08-06 14:47:59
【问题描述】:

我已经有一个树模型视图,其中包含带有标签、文本编辑和复选按钮的列。我要添加的是一个按钮。 这是我卡住的地方:

  1. 在“标志”函数中,我将使用哪个命名空间?
  2. 在“数据”功能中,按钮的作用是什么? (例如在检查按钮的情况下,我使用了Qt::CheckStateRole
  3. 在“数据”函数(返回QVariant)中我应该返回什么?创建的按钮?

我查看了有关此主题的其他答案,最流行的答案建议使用setIndexWidget,但我不确定如何。最后一点,我正在尝试以编程方式执行此操作,而不是使用 UI 设计器。

谢谢!

【问题讨论】:

    标签: c++ qt visual-studio-2013 treeview qpushbutton


    【解决方案1】:

    首先,您似乎对 Qt 的模型/视图框架的工作方式有些困惑。我建议你去查看关于它的 Qt 文档:http://doc.qt.io/qt-5/model-view-programming.html

    您的 3 个问题的答案:

    1. 您不需要在Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex &index) const 中使用任何命名空间。只需返回适合您索引的特定Qt::ItemFlags(即Qt::ItemFlag 的组合)。这与您想要 QPushButton 在您的视图中这一事实无关。我认为您对Qt::ItemIsUserCheckable 标志感到困惑,这使视图显示为复选框。然而,这并不是这个标志真正的作用,实际上它只是告诉视图为用户提供一个改变索引的Qt::CheckStateRole 的方法。视图的默认行为是显示QCheckBox

    2. 没有与按钮相关的角色。您可以使用Qt::CheckStateRoleQt::EditRole,这取决于您选择显示QPushButton 的方法。

    3. QVariant QAbstractItemModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const 中,当roleQt::CheckStateRoleQt::EditRole 时,您可以返回一个布尔值,它将控制QPushButton 的状态。但是,您永远不应该返回 QWidget(或派生的),模型处理数据,而不是它们的显示方式。

    解决方案: 重新实现QAbstractItemDelegate(或QStyledItemDelegate)。重写:

    • createEditor():创建一个QPushButton
    • setEditorData():使用您在QAstractItemModel::data() 中使用的索引和角色设置QPushButton 状态。
    • setModelData():根据QPushButton状态更新模型。

    在您的视图上设置您的委托 (QTreeView::setItemDelegateForColumn())。此时,您只会在版本中获得一个按钮。然后您可以调用QAbstractItemView::openPersistentEditor() 使其始终可见。

    【讨论】:

    • 既然您提到我应该使用 QAbstractItemModel,我是否能够在不重写当前 MTreeModel 的情况下实现它?
    • QAbstractItemModel 是所有模型类的基类,所以我很确定您的 MTreeModel 继承了 QAbstractItemModel,因此我对 QAbstractItemModel 所说的一切都适用于 MTreeModel。
    • 谢谢,我想我现在有了更好的理解。我不太确定我收到的这个错误的问题是什么:返回值类型与函数类型不匹配 QWidget colorDelegate :: *createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) { QPushButton *button = new QPushButton(const_cast(parent));按钮->setText("推");返回按钮; }
    • 试试QWidget *colorDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) { QPushButton *button = new QPushButton(const_cast<QWidget *const>(parent)); button->setText("Push"); return button; }
    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2013-08-28
    • 2018-05-30
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多