I'm trying to scale a QGraphicsItem
, (box
) so that it exactly fits within a pair of lines drawn in/on the background of the QGraphicsView
, as shown below
import sys
from PySide2.QtCore import Qt
from PySide2.QtGui import QPen
from PySide2.QtWidgets import QApplication , QGraphicsScene , QGraphicsView
class MyView(QGraphicsView):
def drawBackground( self , painter , rect ):
size = rect.size()
# Two lines each drawn 10 units from the top and bottom of the view
painter.drawLine( 0 , 10 , size.width() , 10 )
painter.drawLine( 0 , size.height() - 10 , size.width() , size.height() - 10 )
def resizeEvent( self , event ):
size = event.size()
box.setPos( 0 , 10 )
# Box height = 30
# Target height = size.height()- 20
# (20 is total gap of lines in background)
factor = ( size.height()- 20 )/30.0
#print (factor * 30 ) - (size.height() - 20) # Check: prints 0.0 always
box.setScale( factor )
if __name__=="__main__":
app = QApplication(sys.argv)
view = MyView()
view.setAlignment( Qt.AlignLeft | Qt.AlignTop )
view.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
view.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
scene = QGraphicsScene()
scene.setSceneRect( 0 , 0 , 300 , 300 )
box = scene.addRect( 0 , 0 , 10, 30)
pen = QPen()
pen.setCosmetic( True )
box.setPen( pen )
view.setScene( scene )
view.show()
sys.exit(app.exec_())
The problem is that rendering glitches appear especially between the bottom of the box and the lower line in the background when the applicaion is resized. Refer to the circled portion of the screenshot below
Qt version 5.9.5, PySide2 version 5.12.1