How to draw a segment with a gradient color?
Solved
Qt for Python
-
In my application, I have to draw segments connecting several 3D points on a QGraphicsScene. Of course, I cannot draw 3D segments on a 2D surface, thus I'm thinking to draw these segments with a gradient color to show the depth difference between the starting and ending points of each segment.
At the moment I draw each segment with a single color based on one of the 2 point's depth.
To decide the color, I get the minimum and maximum depths among all the points, and then I map the value to a 0-255 range, finally, I use this formula to set the segment color# coords[i][2] is the segment's ending point z value mapped_color = int(self.mapRange(abs(coords[i][2]), abs(z_min), abs(z_max), 0, 255)) # Gives a color between full yellow (superficial segments) and full blue (deep segments) color = QtGui.QColor(255-mapped_color, 255-mapped_color, mapped_color) # Add the segment to the scene self.scene.addLine(QtCore.QLine(p1, p2), color)
Could I draw each segment with a gradient based on the 2 points depth instead of a single color?
-
I have solved using this code
start_mapped_color = self.mapRange( abs(current_position[2]), abs(z_min), abs(self.z_max), 0, 255) end_mapped_color = self.mapRange( abs(coords[i][2]), abs(z_min), abs(self.z_max), 0, 255) start_color = QtGui.QColor( 255-start_mapped_color, 255-start_mapped_color, start_mapped_color) end_color = QtGui.QColor( 255-end_mapped_color, 255-end_mapped_color, end_mapped_color) gradient = QtGui.QLinearGradient(p1, p2) gradient.setColorAt(0, start_color) gradient.setColorAt(1, end_color) gradient_pen = QtGui.QPen(QtGui.QBrush(gradient), 1) self.scene.addLine(QtCore.QLine(p1, p2), pen=gradient_pen)