对于我选择的QListView -> QAbstractListModel,似乎没有内置的选择支持。我必须从头开始写所有的东西吗?在UI中捕获选择事件,将模型项标记为选中,等等?这似乎没有开箱即用的支持。
奇怪的是,有一个QItemSelectionModel确实支持它,但您不能将它与QListView一起使用,因为它不是从QAbstract…派生的。
我的模型类是否应该使用多重继承来同时从QItemSelectionModel和QAbstractListModel继承?否则,我不知道如何避免自己重写这个功能。
我的最终目标是让绘制我的项目的代理知道项目是否在paint和sizeHint函数中被选中。
发布于 2011-03-22 04:56:30
QListView是从QAbstractItemView派生出来的,它有一个获取选择模型的方法:
QItemSelectionModel *selectionModel = myView->selectionModel();这个方法返回一个指向选择模型的指针,它是长期存在的,也就是说,你可以保存指针,连接到它的信号,等等。
发布于 2017-03-13 07:56:50
Daniel给出的答案是正确的,但最好用一个适合初学者的例子来说明:
class MyCustomModel : public QAbstractListModel
{
Q_OBJECT
public:
ImageCollectionModel(QObject *parent, MyCustomCollection *data);
: QObject(parent)
, m_myData(data)
{
}
public slots:
void onSelectedItemsChanged(QItemSelection selected, QItemSelection deselected)
{
// Here is where your model receives the notification on what items are currently
// selected and deselected
if (!selected.empty())
{
int index = selected.first().indexes().first().row();
emit mySelectedItemChanged(m_myData->at(index));
}
}
signals:
void mySelectedItemChanged(MyCustomItem item);
private:
MyCustomCollection *m_myData;
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &) const override;
QVariant data(const QModelIndex &index, int role) const override;
};当您将自定义模型传递给QListView时,这是一个连接它的绝佳机会:
ui->myListView->setModel(m_myModel);
connect(ui->myListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
m_myModel, SLOT(onSelectedItemsChanged(QItemSelection, QItemSelection)));https://stackoverflow.com/questions/5382951
复制相似问题