如何在QListView< - >中检测行选择? QAbstractListModel与Item Delegate?

时间:2011-03-21 20:01:56

标签: c++ qt qt4

我选择的QListView似乎没有内置的选择支持 - > QAbstractListModel。我是否必须从头开始编写所有内容?在UI中捕获选择事件,选择模型项的标记等?似乎没有开箱即用的支持。

奇怪的是,有一个QItemSelectionModel支持这个,但你不能将它与QListView一起使用,因为它不是从QAbstract派生的......

我的模型类是否应该使用多重继承来继承QItemSelectionModel和QAbstractListModel?否则我不知道如何避免自己重写这个功能。

我的最终目标是为绘制我的项目的代理人知道是否在paint和sizeHint函数中选择了该项目。

2 个答案:

答案 0 :(得分:6)

QListView派生自QAbstractItemView,它有一个获取选择模型的方法:

QItemSelectionModel *selectionModel = myView->selectionModel();

此方法返回一个指向选择模型的指针,该指针是长寿命的,即您可以保存指针,连接其信号等。

答案 1 :(得分:-1)

Daniel给出的答案是正确的,但最好用一个适合初学者的例子来展示它:

//vertex shader
#ifdef GL_ES
precision mediump float;
#endif

attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord0;

uniform mat4 u_worldTrans;
uniform mat4 u_projViewTrans;

varying vec2 v_texCoord0;

varying vec3 worldSpaceCoords;

void main() {
worldSpaceCoords = a_position + vec3(.5,.5,.5);
v_texCoord0 = a_texCoord0;
gl_Position = u_projViewTrans * u_worldTrans * vec4(a_position, 1.0);
}

//fragment shader

#ifdef GL_ES
precision mediump float;
#endif

varying vec2 v_texCoord0;

varying vec3 worldSpaceCoords;

void main() {
gl_FragColor = vec4(worldSpaceCoords.x , worldSpaceCoords.y, worldSpaceCoords.z, 1);
 }

当您将自定义模型传递给QListView时,这是一个很好的连接它的机会:

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;
};