PDA

View Full Version : how to draw check box using qstyle in a qgraphicsitem



wagmare
22nd October 2013, 07:31
hi friends,

how to draw checkbox using qstyle in a qgraphicsitem .?
i tried not to use qgraphicsproxy widget so i tried to use qstyle but i was facing a problem in setting the text color of the checkbox.

please correct me if im wrong in this implementation ..



class CheckBoxItem : public QGraphicsObject,public QGraphicsLayoutItem
{
public:
CheckBoxItem(const QString & text,QGraphicsItem *parent =0);
QString m_text;
QRectF boundingRect() const;
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

void mousePressEvent(QGraphicsSceneMouseEvent *event);


QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const;
void setGeometry(const QRectF &rect);


private:
bool m_mousePressed;


};

in .cpp

CheckBoxItem::CheckBoxItem(const QString &text, QGraphicsItem *parent)
: QGraphicsObject(parent),m_mousePressed(false)
{
m_text = text;
}
void
CheckBoxItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QFont font("Serif",8);
painter->setFont(font);

const QStyle *style = QApplication::style();
QStyleOptionButton opt;

opt.state |= m_mousePressed ? QStyle::State_On : QStyle::State_Off;
opt.state |= QStyle::State_Enabled;
// opt.palette = QPalette(Qt::red);
opt.text = m_text;
opt.rect = option->rect;
opt.palette = QPalette(Qt::white);

style->drawControl(QStyle::CE_CheckBox,&opt,painter);

}

QSizeF
CheckBoxItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
return boundingRect().size();
}

void
CheckBoxItem::setGeometry(const QRectF &rect)
{
setPos(rect.topLeft());
}





i dont know how to change the color and font size of the text in check box .. but check box is coming fine ..
please help ..

aamer4yu
22nd October 2013, 12:29
Why do you want to reinvent the wheel ? You can look for QML desktop elements since Qt 5.1

And if you are not using QML, you can anyhow add a widget to QGraphicsScene :)

wagmare
23rd October 2013, 05:36
you can anyhow add a widget to QGraphicsScene
i want to add thousands of checkboxes in my view so i preffered not to go for QGraphicsWidget as to reduce load .. so i tried to make a checkbox graphicsitem with cachemode .

spirit
23rd October 2013, 07:04
QStyleOptionButton inherits QStyleOption. QStyleOption has fontMetrics. So, I guess, you can "feed" your own font metrics in CheckBoxItem:: paint. As for text color, QStyleOption has palette, so you just need to set proper color for QPalette::WindowText or other *Text.

Other thing, you don't see you draw a check box's text using QStyle::drawControl with CE_CheckBoxLabel passed.