簡體   English   中英

無法檢查QListView的項目

[英]Cannot check item of QListView

我正在使用QListView和繼承QAbstractListModel的自定義模型的對話框類。 我列表上的項目是帶有幾個標簽的自定義窗口小部件。

我通過重新實現模型的data()setData()flags()方法設法使每個項目都顯示一個復選框,但是當我運行代碼並單擊與該項目之一關聯的復選框時,該復選框不會t顯示為選中狀態(保持未選中狀態)。

這是我的代碼:

mymodel.h

class MyModel : public QAbstractListModel
{
    Q_OBJECT

public:
    MyModel(QObject *parent);
    int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE ;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
    bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
    Qt::ItemFlags flags(const QModelIndex & index) const Q_DECL_OVERRIDE ;

    QSet<QPersistentModelIndex> checkedItems;
};

mymodel.cpp

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::CheckStateRole)
    {
        if(checkedItems.contains(index))
            return Qt::Checked;
        else
            return Qt::Unchecked;
    }

    return QVariant();
}


bool MyModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    if(role == Qt::CheckStateRole)
    {
        if(value == Qt::Checked)
            checkedItems.insert(index);
        else
            checkedItems.remove(index);

        emit dataChanged(index, index);
    }

    return true;
}


Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
    return QAbstractListModel::flags(index) | Qt::ItemIsUserCheckable;
}

mydelegate.h

class MyDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    MyDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {}
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};

mydelegate.cpp

QSize MyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return QSize(400, 120);
}

在mydialog.cpp的構造函數中

model = new MyModel(this);
ui->list->setModel(model);
ui->list->setItemDelegate(new MyDelegate(this));

我嘗試添加標志Qt::ItemIsEnabledQt::ItemIsEditable但是它沒有任何改變。

盡管我已經閱讀了Qt文檔,但到目前為止我對視圖/模型的實現還不太熟悉。

謝謝!

更准確地說,這就是我的想法

    bool MyModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    if(role == Qt::CheckStateRole)
    {
        if(value == Qt::Checked)
            checkedItems.insert(index);
            self.checkBoxList[index.row()][index.column()].setChecked(True)
        else
            checkedItems.remove(index);
            self.checkBoxList[index.row()][index.column()].setChecked(False)

        emit dataChanged(index, index);
    }

    return true;
}

我只是沒有您所有的代碼,所以我不知道您的self.checkBoxList是如何完成的。 是表的checkBox子級嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM