目标:我希望继承自 QGraphicsItem 的类对象在 QListWidget 中显示为图标。
问题:在列表中,仅显示第一项的图标。
它看起来如何
试图重新定义函数QIconEngine::pixmap,在上面下个断点,但是程序没有进去
这么画
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setBrush(myColor);
painter->setPen(Qt::black);
painter->drawRect(boundingRect());
painter->drawText(QPointF(w / 2,h / 2),myStr);
}
为此,我继承自 QIconEngine
class MyIconEngine : public QIconEngine
{
public:
MyIconEngine(MyItem* item);
// QIconEngine interface
public:
void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) override;
QIconEngine *clone() const override;
private:
MyItem* myItem;
};
其实施
MyIconEngine::MyIconEngine(MyItem* item): myItem(item)
{}
void MyIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
{
myItem->paint(painter,nullptr,nullptr);
}
QIconEngine *MyIconEngine::clone() const
{
return new MyIconEngine(myItem);
}
这样使用
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QListWidget* lw = new QListWidget();
int w = 45;
int h = 45;
lw->setIconSize(QSize(w,h));
MyItem* i1 = new MyItem(w,h,Qt::red,"red");
MyItem* i2 = new MyItem(w,h,Qt::green,"green");
MyItem* i3 = new MyItem(w,h,Qt::blue,"blue");
MyIconEngine* ie1 = new MyIconEngine(i1);
MyIconEngine* ie2 = new MyIconEngine(i2);
MyIconEngine* ie3 = new MyIconEngine(i3);
QIcon* icon1 = new QIcon(ie1);
QIcon* icon2 = new QIcon(ie2);
QIcon* icon3 = new QIcon(ie3);
QListWidgetItem* lwi1 = new QListWidgetItem(*icon1,i1->Str(),lw);
QListWidgetItem* lwi2 = new QListWidgetItem(*icon2,i2->Str(),lw);
QListWidgetItem* lwi3 = new QListWidgetItem(*icon3,i3->Str(),lw);
lw->show();
return a.exec();
}
我的项目.h
class MyItem : public QGraphicsItem
{
public:
MyItem(int width,int height, const QColor& color,const QString& text);
const QString& Str() const
{
return mySrt;
}
// QGraphicsItem interface
public:
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
private:
QColor myColor;
int w;
int h;
QString mySrt;
};
我的项目.cpp
MyItem::MyItem(int width, int height, const QColor &color,const QString& text):w(width),h(height),myColor(color),mySrt(text)
{}
QRectF MyItem::boundingRect() const
{
return QRectF(0,0,w,h);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setBrush(myColor);
painter->setPen(Qt::black);
painter->drawRect(boundingRect());
painter->drawText(QPointF(w / 2,h / 2),mySrt);
}