user4520
user4520

Reputation: 3457

Unable to set a tooltip with setData when using QListView with QStringListModel

I'm using a QListView widget in my application with QStringListModel as the model. Here's the complete code:

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include <QStringListModel>
#include <QListView>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setFixedSize(400, 400);

    auto listView = new QListView;
    setCentralWidget(listView);

    auto model = new QStringListModel;
    listView->setModel(model);

    QStringList list;
    list << "item 1" << "item 2";
    model->setStringList(list);
    auto idx = model->index(0);
    model->setData(idx, "Some tooltip", Qt::ToolTipRole);
    model->setData(idx, "actually, item 11", Qt::DisplayRole);
}

The result:

enter image description here

As can be seen, the second setData call succeeds and the item text is changed, but the tooltip simply doesn't work; I can hover my mouse as much as I want over the first entry, and nothing happens.

What am I doing wrong?

Upvotes: 1

Views: 1539

Answers (1)

jpnurmi
jpnurmi

Reputation: 5836

The data structure of QStringListModel is a simple list of strings. It handles only Qt::DisplayRole and/or Qt::EditRole. If you check the return value of setData(), you'll see that it returns false for Qt::ToolTipRole. You might want to switch to a model that can handle multiple roles, such as QStandardItemModel.

Upvotes: 4

Related Questions