سؤال

I have some kind of histogram drawn with QGraphicsRectItem; some of these rectangles are long, some short. While it is no problem to select a long rectangle, one might have difficulties with the short ones.

So I was wondering if there is a way to specify custom area that would trigger mousePressEvent for the item, so rectangles would have the same size selection area.

Apart from rectangles I also draw some text on the same line. Would it be helpful to group them somehow and write mousePressEvent for the group instead?

Thank you!

هل كانت مفيدة؟

المحلول

It would be useful to see an example image of what you're asking, but I think I know what mean.

Personally, I'd just create my own class, inherited from QGraphicsItem (or QGraphicsObject, if you want signals and slots). This class can then provide a boundingRect() of the full area that you want to represent the area to be selected, but the paint() function only draw the visible part of the bar. Something like this: -

class Bar: public QGraphicsItem
{
    Q_OBJECT

    public:
        Bar(int x, int y, int width, int height, int visibleBarHeight);

        // returns the area of the object
        QRectF boundingRect() const;

        void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); 
};

In the paint function, you would draw a rect up to the visible bar height, but in boundingRect, return the full rect. That way, the bar could visibly be very small, but the object is of full height and would respond to mouse selection above the visible area of the bar.

As for the text, you could either add it as a child to this object and signal the parent when it gets selected, or extend the boundingRect of this Bar class and render it in the paint function.

Note that boundingRect is the area represented by the object, in local coordinates. If you have an object that isn't defined by a rectangle, you'd also want to implement the shape() function. By default, shape() calls boundingRect().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top