当前位置: 代码迷 >> QT开发 >> Qt中model/view继承QAbstractListModel始终显示不出来,请帮忙看code哪里有有关问题。多谢
  详细解决方案

Qt中model/view继承QAbstractListModel始终显示不出来,请帮忙看code哪里有有关问题。多谢

热度:82   发布时间:2016-04-25 03:16:46.0
Qt中model/view继承QAbstractListModel始终显示不出来,请帮忙看code哪里有问题。谢谢。
如下代码,希望在list中显示出录入坐标组的x坐标。但是运行后只是显示一个空的面板,也没有报错。不知问题处到哪里了。。
头文件:

#ifndef TESTLISTMODEL_H
#define TESTLISTMODEL_H

#include <QAbstractListModel>

#include <QList>
#include <QPointF>

class TestListModel : public QAbstractListModel
{
    Q_OBJECT
public:
    explicit TestListModel(QList<QPointF>* list, QObject *parent = 0);

    virtual int rowCount(const QModelIndex &parent) const;

    virtual QVariant data(const QModelIndex &index, int role) const;

private:
    QList<QPointF>* pPointList;

};

实现代码:

#include "testlistmodel.h"

TestListModel::TestListModel(QList<QPointF> *list, QObject *parent) :
    QAbstractListModel(parent)
{
    pPointList = list;
}

int TestListModel::rowCount(const QModelIndex &parent) const
{
    //return pList->count();
    //return pStrList->count();
    return pPointList->count();
}

QVariant TestListModel::data(const QModelIndex &index, int role) const
{
    if ( !index.isValid()) {
        return QVariant();
    }

    if (Qt::DisplayRole == role)
        return pPointList->at(index.row()).x();
    }
}


main文件:

#include <QApplication>

#include "flowchartsymbolpicker.h"

#include "testlistwidget.h"
#include "testlistmodel.h"
#include <QListView>


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QList<QPointF> coordinates;
    coordinates << QPointF(0.0, 0.009)
                << QPointF(0.2, 11.0)
                << QPointF(0.4, 15.4)
                << QPointF(0.6, 12.9)
                << QPointF(0.8, 8.5)
                << QPointF(1.0, 7.1)
                << QPointF(1.2, 4.0)
                << QPointF(1.4, 13.6)
                << QPointF(1.6, 22.2)
                << QPointF(1.8, 22.2);

    TestListModel model(&coordinates);
    QListView v;
    v.setModel(&model);
    //v.setAlternatingRowColors(true);
   // v.setWindowTitle(QObject::tr("test"));
    v.show();

    return app.exec();
}

------解决方案--------------------
引用:
谢谢,为什么非要加这么一句?

第一,函数有返回值,但是你原来的写法不是所有情况都有返回值的,写法有问题;第二,Qt在显示的时候会直接调用你所派生类的data函数,ItemDataRole有很多属性,如果你没有实现,Qt就不知道这个值怎样取了,想了解详细的话还是看下源码吧
  相关解决方案