我有一个来自QGraphicsItem的类RadBox子类。我希望项目具有不同的背景和前景色,具体取决于其场景是显示、打印还是复制到剪贴板。以下是该项目的paint()
方法:
void RadBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
if(isSelected()) painter->setPen(grayPen);
else painter->setPen(blackPen);
if(standing!=0) painter->setBrush(redBrush);
else painter->setBrush(grayBrush);
painter->drawRoundedRect(-35, -30, 70, 60, 3, 3);
painter->setFont(fnt);
painter->drawText(QRectF(-35,-10,70,20),Qt::AlignCenter,QString::number(box_number));
painter->setFont(fnt2);
painter->drawText(QRectF(-35,5,70,20),Qt::AlignCenter,QString::number(power));
}
复制到剪贴板:
void Scheme::on_copyButton_clicked()
{
QPixmap pm(scene.itemsBoundingRect().width()*3,scene.itemsBoundingRect().height()*3);
QPainter pnt;
pnt.begin(&pm);
scene.render(&pnt);
pnt.end();
QApplication::clipboard()->setPixmap(pm,QClipboard::Clipboard);
}
印刷:
void Scheme::print_preview(QPrinter* printer)
{
QPainter pnt;
pnt.begin(printer);
scene.render(&pnt);
pnt.end();
}
如何让物品知道场景是被绘制、打印还是复制?
回答自己:painter->device()
有一个成员devType()
。
switch(painter->device()->devType())
{
case QInternal::Widget:
if(isSelected()) painter->setPen(grayPen);
else painter->setPen(blackPen);
if(standing!=0) painter->setBrush(redBrush);
else painter->setBrush(grayBrush);
break;
case QInternal::Pixmap:
case QInternal::Printer:
painter->setPen(blackPen);
painter->setBrush(QBrush(Qt::white));
break;
default:
break;
}