I have a QScrollArea that contains a painter widget. This painter widget needs to draw several boxes at different horizontal x locations. However, I’d like there to always be a “legend” on the left of the screen when scrolling.
I achieved this by calling QScrollArea.horizontalScrollBar().value()
, however when scrolling, the repaint method seems to draw multiple lines when I use this horizontalScrollBar().value()
to get the scroll pos.
StackOverflow won’t let me upload the gif, but when I scroll to the left or right, the line drawn using horizontalScrollBar().value()
is drawn multiple times in different locations. If you stop scrolling and resize the window, the paint event corrects itself and draws one single line on the left of the screen. Does anyone know how to fix this or what the scrollevent signal is so I can manually have it call a repaintevent?
Here is my example code:
Example program:
class Capacity_Drawer(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(10000, 10000)
self.setMinimumSize(1000, 500)
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
if self.scroll_area:
painter.setPen(QPen(QColor("Red"), 5))
x_pos = self.scroll_area.horizontalScrollBar().value()+1
painter.drawLine(x_pos, 0, x_pos, 500)
rect = QRectF(800, 0, 100, 100)
painter.drawRect(rect)
def set_scroll_area(self, scroll_area:QScrollArea):
"""Set a reference to the parent scroll area."""
self.scroll_area = scroll_area
class Capacity_Scroll_Area(QScrollArea):
def __init__(self):
super().__init__()
self.capacity_viewer = Capacity_Drawer()
self.capacity_viewer.set_scroll_area(self)
# Set the GanttWidget as the scrollable area content
self.setWidget(self.capacity_viewer)
self.setWidgetResizable(True) # Allow resizing of the widget within the scroll area
class window(QMainWindow):
def __init__(self):
super().__init__()
cap_scroll_area = Capacity_Scroll_Area()
self.setCentralWidget(cap_scroll_area)
app = QApplication(sys.argv)
# Create and show the main window
window = window()
window.show()
sys.exit(app.exec())