即然这样就把我的相关代码贴出来,
代码写的不好,高手有空的话帮忙看看,能不能看出点端倪来。
------------------
1. 构造Model代码
void FrameRSSItems::fillAllItems(QSqlQuery &query)
{
rssModel->clear();//清空Model
ListItem *item;
while(query.next())
{
item = new ListItem;
item->setValue(query.record().field("readed").value().toBool(),
query.record().field("title").value().toString(),
query.record().field("description").value().toString(),
query.record().field("url").value().toString());
rssModel->addItem(item);//添加项
}
}
--------------------
2. 获取值
void FrameRSSItems::onDoubleClick(const QModelIndex & index)
{
emit selectionChanged(index.data(Qt::UserRole + 1).toString());
ListItem *item= static_cast<ListItem*>(index.internalPointer());
QString str = item->caption();//这个地方出错,但是对于另外一个基本数据类型没有报错
qDebug()<<str;
}
--------------------
3. 类定义
class ListItem
{
public:
ListItem():m_caption(""),m_description(""),m_url(""){}
const QString &caption() const;
QString description() const;
QString url() const;
bool readed() const;
void setValue(bool readed, const QString &caption, const QString &description, const QString &url);
void setReaded(bool value);
bool selected;
private:
bool m_readed;
QString m_caption,
m_description,
m_url;
};
4. 类实现
const QString & ListItem::caption() const
{
return m_caption;
}
QString ListItem::description() const
{
return m_description;
}
QString ListItem::url() const
{
return m_url;
}
bool ListItem::readed() const
{
return m_readed;
}
void ListItem::setValue(bool readed, const QString &caption, const QString &description, const QString &url)
{
m_readed = readed;
m_caption = caption;
m_description = description;
m_url = url;
selected = false;
}
void ListItem::setReaded(bool value)
{
m_readed = value;
}
----------------------------
5.以下信息用来在QTableView中显示,是正确的。。。
QVariant ListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
ListItem *item = static_cast<ListItem*>(index.internalPointer());
if (index.column()==0)
{
switch(role)
{
case Qt::DisplayRole:
return item->caption();
case Qt::DecorationRole:
if (item->readed())
return readed;
else
return unRead;
//这里需要添加自定义枚举变量
//用于获取item->selected的值
case Qt::UserRole:
return item->readed();
case Qt::FontRole:
if (!item->readed())
return *m_bold;
return *m_normal;
case Qt::CheckStateRole:
if (item->selected)
return Qt::Checked;
else
return Qt::Unchecked;
case Qt::UserRole+1:
return item->url();
default:
return QVariant();
}
}
if (index.column()==1)
{
switch(role)
{
case Qt::DisplayRole:
return item->description();
case Qt::FontRole:
if (!item->readed())
return *m_bold;
return *m_normal;
case Qt::UserRole+1:
return item->url();
default:
return QVariant();
}
}
return QVariant();
}