0

私のプロジェクトでは、QTreeViewからのアイテムを表示していQStandardItemModelます。各アイテムには、いくつかの UserRole に格納されたデータがあります。

QStandardItem* item = new QStandardItem();
item->setIcon(iconByte);
item->setData(3, Qt::UserRole+1);
item->setData(name, Qt::UserRole+2);
item->setData(data, Qt::UserRole+3);
... and so on

ユーザーが項目をダブルクリックすると、2 行の編集を含むダイアログが表示され、ユーザーは UserRole データの一部を編集できます。編集が終了すると、編集は何らかのロジックを介して実行され、新しい UserRole データに基づいて表示名が生成されます。

ただし、これはすぐに非常に退屈になります。ダイアログが絶えずポップアップするなど、遅くて醜いソリューションです。

ダイアログを完全に削除し、アイテム自体の中に行編集ウィジェットを表示したいと思います。デフォルトでは、アイテムをダブルクリックして編集すると、DISPLAY ロールを変更するための行編集ウィジェットが 1 つだけ表示されます。ただし、2 つのユーザーの役割を変更するには、2 行の編集が必要です。そして、通常のロジックが続きます。

の編集項目部分を変更するにはどうすればよいQTreeViewですか?

御時間ありがとうございます!

4

1 に答える 1

2

これを解決するには、 QStyledItemDelegateのカスタム サブクラスを使用します。あなたの近くのどこかで、ユーザーの役割を切り替えるQTreeViewことができます。QComboBoxカスタム デリゲートは、現在どのユーザー ロールが選択されているかを何らかの方法で通知され、モデル内のデータを更新するメソッドをインターセプトして適切なロールを設定します。

実装例 (テストされていないため、タイプミスやエラーが含まれている可能性があります):

class RoleSwitchingDelegate: public QStyledItemDelegate
{
public:
    explicit RoleSwitchingDelegate(QComboBox * roleSwitcher, QObject * parent = 0);

    virtual void setEditorData(QWidget * editor, const QModelIndex & index) const Q_DECL_OVERRIDE;
    virtual void setModelData(QWidget * editor, QAbstractItemModel * model,
               const QModelIndex & index) const Q_DECL_OVERRIDE;
private:
    QComboBox * m_roleSwitcher;
};

RoleSwitchingDelegate::RoleSwitchingDelegate(QComboBox * roleSwitcher, QObject * parent) :
    QItemDelegate(parent),
    m_roleSwitcher(roleSwitcher)
{}

void RoleSwitchingDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const
{
    // Assuming the model stores strings for both roles so that the editor is QLineEdit
    QLineEdit * lineEdit = qobject_cast<QLineEdit*>(editor);
    if (!lineEdit) {
        // Whoops, looks like the assumption is wrong, fallback to the default implementation
        QStyledItemDelegate::setEditorData(editor, index);
        return;
    }

    int role = m_roleSwitcher->currentIndex();
    QString data = index.model()->data(index, role).toString();
    lineEdit->setText(data);
}

void RoleSwitchingDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
    // Again, assuming the model stores strings for both roles so that the editor is QLineEdit
    QLineEdit * lineEdit = qobject_cast<QLineEdit*>(editor);
    if (!lineEdit) {
        // Whoops, looks like the assumption is wrong, fallback to the default implementation
        QStyledItemDelegate::setModelData(editor, model, index);
        return;
    }

    int role = m_roleSwitcher->currentIndex();
    QString data = lineEdit->text();
    model->setData(index, data, role);
}

デリゲートを取得したら、それをビューに設定するだけです。

view->setItemDelegate(new RoleSwitchingDelegate(roleSwitchingComboBox, view));
于 2016-12-29T08:00:44.087 に答える