我的模型继承自QAbstractItemModel:
class Plugin: public QObject
{
Q_OBJECT
public:
explicit Plugin(QObject *parent=0);
~Plugin();
const QIcon icon();
void setIcon(const QString &ico);
private:
QIcon mIcon;
};
class PluginsModel: public QAbstractItemModel
{
Q_OBJECT
public:
explicit PluginsModel(QObject *parent=0);
~PluginsModel();
protected:
QList<Plugin*> mList;
};
我只想创建一次QIcon实例,而只是在数据中执行:
QVariant PluginsModel::data(const QModelIndex &index, int role) const
{
if (mList.isEmpty())
return QVariant();
Plugin *it = static_cast<Plugin*>(index.internalPointer());
switch (role ) {
case Qt::DecorationRole:
switch (index.column()) {
case 0:
return it->icon();
break;
default:
break;
}
}
return QVariant();
}
所以setIcon函数如下所示:
const QIcon Plugin::icon()
{
return mIcon;
}
void Plugin::setIcon(const QString &ico)
{
mIcon = QIcon(ico);
}
用法:
Plugin *p = new Plugin(this);
p->setIcon(":/images/16/amarok.png");
mPlugins->add(p);
问题是它不起作用(图标未绘制)。但是,如果我将setIcon更改为:
void Plugin::setIcon(QIcon &ico)
{
mIcon = ico;
}
...以及用法:
Plugin *p = new Plugin(this);
QIcon i(":/images/16/amarok.png");
p->setIcon(i);
mPlugins->add(p);
...然后它工作正常。任何人都可以告诉我从外部传递QIcon引用和从图像路径参数创建类内部引用之间的区别是什么?