我有从 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 引用和从图像路径参数在类内部创建引用有什么区别?