How to detect Qt mouse events only over QPainted objects - qt

I am attempting to produce a compass widget programatically that looks much like this:
I want each "slice" of the compass to act as a button for interaction w/ the rest of the app. To that end, I figured making them out of QAbstractButtons made the most logical sense, and started down this path:
class compassWedge(QAbstractButton):
def __init__(self, start_angle, parent=None):
super().__init__(parent)
self.start = start_angle
self.setFixedSize(550, 550)
self.setMouseTracking(True)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
brush = QBrush()
if self.underMouse():
brush.setColor(Qt.black)
else:
brush.setColor(Qt.white)
pen = QPen(Qt.black)
pen.setWidth(5)
painter.setBrush(brush)
painter.setPen(pen)
painter.drawPie(25, 25, 500, 500, self.start, 45 * 16)
painter.end()
class compassApplet(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(550, 550)
self.wedges = []
for start in range(0, 360 * 16, 45 * 16):
self.wedges.append(compassWedge(start, self))
And visually this works perfectly so far:
The problem is, for underMouse(), the entirety of the 550x550 slice widget area is considered. I want instead to detect when the mouse is inside the pixels generated within the paintEvent for each slice, i.e. the pie area created by painter.drawPie(...) in each object.
How can I accomplish this without having to do complicated geometry to check mouse position against pie-shaped areas?

Method 1: perform the geometric calculations yourself:
How can I accomplish this without having to do complicated geometry to check mouse position against pie-shaped areas?
Doing the geometry check yourself isn't that difficult:
Check if the mouse is inside the circle, i.e. distance between mouse and center of circle <= radius of circle.
Use atan2 to calculate the angle and use it to determine the correct segment
Method 2: Use QPieSeries
If you really do not want to implement the geometric calculations yourself, visualising the compass using a QPieSeries may be a solution as it provides a hovered function. However, it may be (more) difficult to obtain the exact desired visual representation.

Related

(Qt) Render SVG with custom color

I want to render a SVG icon in a QPixmap by choosing the drawing color.
This is my code using PyQt:
def svg_to_pixmap(svg_filename: str, width: int, height: int, color: QColor) -> QPixmap:
renderer = QSvgRenderer(svg_filename)
pixmap = QPixmap(width, height)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
painter.setPen(QPen(color))
renderer.render(painter)
painter.end()
return pixmap
And a test code to display the pixmap:
app = QApplication([])
pixmap = svg_to_pixmap("test.svg", 512, 512, Qt.GlobalColor.red)
label = QLabel()
label.setStyleSheet("background-color: yellow;")
label.setPixmap(pixmap)
label.show()
app.exec()
The issue is that painter.setPen has no effect as expected (the drawing remains black). The background is transparent as expected and we can see the label background color behind.
An example of SVG file to test here
My configuration: Ubuntu22.10, X11, PyQt6.3.1
The answer is not simple. But, as long as you are completely sure that you only want to use the shape (or mask) of the original SVG, then it is feasible.
The reason for which setting the pen doesn't change the result is that SVG is a vector image format: it usually explicitly tells the colors of anything it wants to draw, so, setting the painter pen is almost useless, unless the SVG content is so simple to not specify it, which is clearly not the case: icons normally define colors of their shapes, and for good reasons.
The problem comes when trying to understand compositing and the possible alternatives that QPainter provides.
To be honest, even after trying to put efforts in understanding the results and associating them with the QPainter.CompositionMode enums, I still need to testing and checking in order to understand the proper mode I need.
What you probably need is the CompositionMode_SourceIn, which is cryptically explained in the documentation:
The output is the source, where the alpha is reduced by that of the destination.
As far as I can understand, the source is what is going to be painted, while the destination is what was previously painted (consider the source as a brush painting, and the destination as the canvas on which you paint).
With that in mind, we need to use the original svg as the destination and fill the whole pixmap with the color we want. Since only the alpha of the destination will be used (the visible part of the svg), we will be practically doing some sort of "stencil".
def svg_to_pixmap(svg_filename: str, width: int, height: int, color: QColor) -> QPixmap:
renderer = QSvgRenderer(svg_filename)
pixmap = QPixmap(width, height)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
renderer.render(painter) # this is the destination, and only its alpha is used!
painter.setCompositionMode(
painter.CompositionMode.CompositionMode_SourceIn)
painter.fillRect(pixmap.rect(), color)
painter.end()
return pixmap
Which seems to give the wanted result:

Subpixel accuracy when drawing vector graphics in Qt?

I have written a small test script in Python and PySide6 to test the vector graphics capabilities of Qt, in particular the accuracy when it comes to the exact shapes and positions of the drawn figures. My first test was to draw a disk with a slightly smaller disk within it:
import sys
from PySide6.QtCore import Qt, QPoint
from PySide6.QtWidgets import QApplication, QWidget
from PySide6.QtGui import QPainter, QBrush
radii_difference = 1
x_offset = 0
class MyWidget(QWidget):
def paintEvent(self, event):
self.setWindowTitle("radii_difference: {}; x_offset: {}".format(radii_difference, x_offset))
print("radii_difference: {}; x_offset: {}".format(radii_difference, x_offset))
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, on=True)
painter.setPen(Qt.NoPen)
painter.setBrush(QBrush(Qt.red))
painter.drawEllipse(QPoint(300, 250), 200, 200)
painter.setBrush(QBrush(Qt.blue))
painter.drawEllipse(QPoint(300 + x_offset, 250), 200 - radii_difference, 200 - radii_difference)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
As can be seen in the code, I call the difference of the radii radii_difference, and I also create another variable x_offset to parameterize the position of the inner disk. When trying with two different values for radii_difference—0.5 and 1—I see no difference in the thickness of the red outline of the blue disk at all, which indicates that painter.drawEllipse rounds down the rx and ry arguments to the closest integer.
Likewise, if I change x_offset from 0 to 0.5, PyCharm highlights 300 + x_offset and gives me the mouse-over text "Expected type 'int', got 'float' instead", indicating that QPoint (and therefore also QPainter.drawEllipse) only accepts integer (center point) coordinates, and when I run the application, I see no difference from the previous figure (in particular, if drawEllipse would have supported non-integer center point coordinates, the red outline would have been about three times as thick on the left side than on the right side, but it instead appear equally thick everywhere).
Both of these discoveries makes it feel like QPainter offers very limited accuracy of the positions and sizes of drawn objects (I guess this translates to other shapes as well, not only ellipses).
Is there some way to increase this accuracy somehow when using QPainter? If not, is there some alternative way to draw vector graphics in Qt (especially with PySide6, but I might consider switching to C++ if that offers greater possibilities) that gives me subpixel accuracy of positions, shapes and sizes of drawn object?
I found the answer by looking at the method in the C++ API; there it exists in five different overloads, two of which can offer subpixel accuracy: void drawEllipse(const QRectF &rectangle) and void drawEllipse(const QPointF &center, qreal rx, qreal ry)
I tested substituting QPointF for QPoint, and it solved the problem.

Make QGraphicsView do smooth centerOn

i am not really newbie in Qt, but there are a few things i don't know...
I am programming in Python, but feel free to post your answers in ANY language.
So, i have a few QGraphicsItem (s), positioned inside a QGraphicsScene, the scene is viewed with a normal QGraphicsView. Everything is normal.
My scene is very large, 10,000 x 10,000 pixels, all graphic items are scattered around.
For example :
# Creating Scene object.
scene = QtGui.QGraphicsScene()
scene.setSceneRect(0, 0, 10000, 10000)
# Creating View object.
view = QtGui.QGraphicsView()
view.setScene(scene)
# Adding some objects to scene.
# scene.addItem(...)
# ...
# The list of items.
items = scene.items()
# This is how i center on item.
view.centerOn(some_item)
view.fitInView(some_item, Qt.KeepAspectRatio)
My question is, how can i center the view on every item, using something similar to centerOn, but smoothly ?
Currently, centerOn goes FAST on next item, i want to move it slooowly, maybe using QPropertyAnimation with easing curve ?
I tried to move the view to the next item using view.translate(1, 1) in a big cicle, but the movement is too fast, just like centerOn.
I tried to put some waiting with time.sleep(0.01) between the translating, but the windows blocks untill the cicle exists... so it's bad.
Thank you very much !
I once used a QTimeLine (with EaseInOutCurve), connected it to a slot, and then used that value to translate the view rect, like this:
const QRectF r = ...calculate rect translated by timeline value and trajectory...
view->setSceneRect( r );
view->fitInView( r, Qt::KeepAspectRatio );
For the trajectory I used a QLineF with start and end position for the smooth scrolling.
Then one can use the value emitted by timeline nicely with QLineF::pointAt().
In my case I needed to set both SceneRect and fitInView to make it behave like I wanted.
I solved my problem by placing a high value on setSceneRect. Then I centralize the scene on an object or position.
example:
this->ui->graphicsView->setSceneRect (0,0,100000000, 100000000);
this->ui->graphicsView->centerOn(500,1030);
With the setSceneRect size GraphicsView does not work right.

How to use custom drawing in QGraphicsViews in PyQt?

I need to view QGraphicsScene in 2 QGraphicsViews with condition that they have different scale factors for items in scene. Closest function which I found is drawItems(), but as far I can understand, it must be called manually. How to repaint views automatically?
I have these two code fragments in program:
class TGraphicsView(QGraphicsView):
def __init__(self, parent = None):
print("__init__")
QGraphicsView.__init__(self, parent)
def drawItems(self, Painter, ItemCount, Items, StyleOptions):
print("drawItems")
Brush = QBrush(Qt.red, Qt.SolidPattern)
Painter.setBrush(Brush)
Painter.drawEllipse(0, 0, 100, 100)
...
Mw.gvNavigation = TGraphicsView(Mw) # Mw - main window
Mw.gvNavigation.setGeometry(0, 0, Size1, Size1)
Mw.gvNavigation.setScene(Mw.Scene)
Mw.gvNavigation.setSceneRect(0, 0, Size2, Size2)
Mw.gvNavigation.show()
__init__ works, Mw.gvNavigation is displayed and there are Mw.Scene items in it, but drawItems() isn't called.
The drawItems methods on QGraphicsView and QGraphicsScene objects have been deprecated in Qt 4.6 and have to be enabled using the IndirectPainting flag, but I would't recommend using deprecated features.
Here's another stack overflow question on a similar issue. One of the answers shows how to make the paint methods on individual items in a scene aware of which view is painting them, and use different paint code when drawn in different views.

Is there a way to make drawText() update a QPicture's bounding rect?

Drawing on a QPicture should update its bounding rect. Like this:
>>> picture = QPicture()
>>> painter = QPainter(picture)
>>> picture.boundingRect()
QRect(0,0,0,0)
>>> painter.drawRect(20,20,50,50)
>>> picture.boundingRect()
QRect(20,20,50,50)
But if I draw text on it, the bounding rect isn't updated:
>>> picture = QPicture()
>>> painter = QPainter(picture)
>>> picture.boundingRect()
QRect(0,0,0,0)
>>> painter.drawText(10,10, "Hello, World!")
>>> picture.boundingRect()
QRect(0,0,0,0)
Obviously, it doesn't update the bounding rect.
Is there a way to make it repsect drawn text or do I have to do it manually? (Not too hard, but I hope that Qt can assist me here.)
Take a look at these overload methods, where you must specify the Bounding Rectangle after the text parameter (which is apparently different than the rectangle in the first argument's position):
Draws the given text within the
provided rectangle according to the
specified flags. The boundingRect (if
not null) is set to the what the
bounding rectangle should be in order
to enclose the whole text.
QPainter.drawText (1), QPainter.drawText (2)
Update:
It appears if you want to generate a bounding rectangle for the drawText() method in advance, you just call the boundingRect() method on QPainter, which does the following:
Returns the bounding rectangle of the
text as it will appear when drawn
inside the given rectangle with the
specified flags using the currently
set font(); i.e the function tells you
where the drawText() function will
draw when given the same arguments.
If the text does not fit within the
given rectangle using the specified
flags, the function returns the
required rectangle.
QPainter.boundingRect
I linked to BoundingRect with QRectF output, but the information applies to the other versions as well.
So basically, pass the result of QPainter.boundingRect() into the boundingRect parameter of the QPainter.drawText() method (the second QRect argument).
Update 2:
I APOLOGIZE PROFUSELY for being so damn dense. I forgot that drawText works differently in PyQt than in Qt. The bounding rectangle is RETURNED by the drawText function (not passed in like Qt) and in addition, you have to specify alignment flags before you get a bounding rectangle given back to you. (I even included the p.end() as per Aaron Digulla's comment):
pic = Qt.QPicture()
p = QtGui.QPainter(pic)
brect = p.drawText(10,10,200,200, QtCore.Qt.AlignCenter, "blah")
p.end()
print brect
print pic.boundingRect()
Here is the output:
PyQt4.QtCore.QRect(100, 103, 20, 14)
PyQt4.QtCore.QRect(0, 0, 0, 0)
So it appears you will have to set the bounding rectangle yourself, though at least it is returned to you by the output of the drawText() method when passing in flags.
This does not seem like ideal behaviour, that you would have to set the bounding rectangle yourself. I hope someone else has the answer you're looking for, but I suspect you may want to report this bug.
Painting doesn't change the size of something in Qt. The main reason is this:
A component has to paint itself
The paint triggers a resize
The resize triggers painting -> endless loop
So the resize has to happen during the layout phase. After that, the bounds should not change.
To solve your problem, use QFontMetric to figure out how big your text is going to be during or close to the construction of your picture and then resize it accordingly.
[EDIT] Hm ... try to call end() before requesting the bounding rect. If that works, you've found a bug (can't see a reason why the bounding rect should not exist as you add elements...)

Resources