April 28, 2012

mahesh438 mahesh438
Lab Rat
45 posts

multiple colors in a single rectitem

 

hi,some one please help me .Is it possible to put two are more colors in a single rectItem .for an example QRect(0,0,100,100) this is my actual rectitem i want to put half area red and remaing half green.please help with some sample code

5 replies

April 28, 2012

leon.anavi leon.anavi
Mad Scientist
1200 posts

Just draw a red rectangle and a green rectangle next to it.

 Signature 

http://anavi.org/

April 28, 2012

Sam Sam
Robot Herder
668 posts

Hi ,
you can try the following code :

  1. QRect myRect(0,0,100,100);
  2. QPainter painter(this);
  3. painter.fillRect(myRect.x(),myRect.y(),myRect.width()/2,myRect.height(),Qt::red);
  4. painter.fillRect(myRect.width()/2,myRect.y(),myRect.width(),myRect.height(),Qt::green);

and if you are overriding the paint() event of a component/widget then u can write:

  1. painter->fillRect(QRect(option.rect.x(),option.rect.y(),option.rect.width()/2,option.rect.height()),Qt::red);
  2. painter->fillRect(QRect(option.rect.width()/2,option.rect.y(),option.rect.width(),option.rect.height()),Qt::green);

April 29, 2012

mahesh438 mahesh438
Lab Rat
45 posts

Thanks to all. “SOUMITRA” your code is very useful for me.actually i am working on QGraphicsrectItems.how can i do the same “color “ thing on the QGRaphicsRectItem instead of QRect

April 29, 2012

Sam Sam
Robot Herder
668 posts

Hi,

If you need to subclass QGraphicsItem or QGraphicsRectItem as per your requirements, and then override the paint() function.

For Eg:
.h

  1. class MyRectItem : public QGraphicsItem
  2. {
  3.  
  4. public:
  5.     MyRectItem();
  6.    
  7.     QRectF boundingRect() const;
  8.     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
  9.  
  10. };

.cpp
  1. QRectF MyRectItem::boundingRect() const
  2. {
  3.     return QRectF(0,0,100,100);
  4. }
  5.  
  6. void MyRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  7. {
  8.     painter->fillRect(boundingRect().x(),boundingRect().y(),boundingRect().width()/2,boundingRect().height(),Qt::red);
  9.     painter->fillRect(boundingRect().width()/2,boundingRect().y(),boundingRect().width(),boundingRect().height(),Qt::green);
  10.  
  11. }

April 29, 2012

ZapB ZapB
Hobby Entomologist
1423 posts

Or just use 2 QGraphicsRectItems with a common parent.

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

 
  ‹‹ SQLite returns result for sqlite_master but not for a user table ??????????      QAudioInput -- error underrun? HOW? ››

You must log in to post a reply. Not a member yet? Register here!