开发者

Accessing custom model data from another widget when an item in view is clicked

I have a QListView that sets a custom QAbstractListModel as the model. The model loads data from a database and puts it all in a QList<QHash<QString, QString> > dataList data structure. Each QHash<QString, QString> data contains stuff like data["id"] and data["name"]. The data["name"] value is passed to the QListView via the model's data() method. Now what I want to do is access the QHash<QString, QString> belonging to the clicked item from another widget when an item is clicked in the QListView.

So something like this...

connect(view, SIGNAL(clicked(...)), someOtherWidget,开发者_运维问答 SLOT(foo(...))

And in foo() we could do for example...

void someOtherWidget::foo(const QHash<QString, QString>& customData) { QMessageBox::information(this, "User ID", customData["id"]; }

And it would display the item's id in the message box.


You can use special role in your data() function. data() will then return the QHash

QVariant yourModel::data( QModelIndex index, int role )
{
    ....
    if( role == myCustomRole )
    {
        return QVariant::fromValue( myData[ index.row ] )
    }
    ....
}

Then in your foo function

QHashMap<QString, QString> & model = 
    view->model()->data( view->selectedIndex(), myCustomRole )
        .value< QHashMap<QString, QString> >();


A QListView class has a handy clicked() signal, that passes QDataIndex for an item that was clicked. Just define a clicked slot and a custom signal for your model:

signals:
    void elementSelected (QStringHash _element); // Also, there's a string hash
                                                 // class, so save the <>
public slots:
    void onClicked (const QModelIndex &_index);

and create a respective slot for your widget:

public slots:
    void onElementSelected (QStringHash _element);

In onClicked, emit the elementSelected() signal

void YourModel::onClicked (const QModelIndex &_index)
{
    elementSelected (dataList (_index.row())
}

Finally, just connect all your signals: clicked() from list view to your model and elementSelected() from your model to your custom widget. If you really need the view to emit elementSelected() signal, and not the model, you'll have to define a class derived from QListView with a similar signal and connect elementSelected() signal from the model to elementSelected() signal from this new class. It's perfectly okay to connect signals to each other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜