PyQt4滚动故障

时间:2013-10-01 19:47:22

标签: python pyqt pyqt4 repaint qgraphicsview

我写了一个小应用程序,它使用了QGraphicsView。您可以缩放和平移视图。问题是,当您放大(因此视图将大于窗口),并且您平移视图时,过时的毛刺显示(picture

我的代码:

import sys
import math
from PyQt4 import QtGui, QtCore



class GraphWidget(QtGui.QGraphicsView):
    def __init__(self):
        super(GraphWidget, self).__init__()
        scene = QtGui.QGraphicsScene(self)
        scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
        scene.setSceneRect(0, 0, 400, 400)
        self.setScene(scene)
        self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
        self.setViewportUpdateMode(QtGui.QGraphicsView.BoundingRectViewportUpdate)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        self.sFactor=1
        self.scale(1, 1)
        self.setMinimumSize(400, 400)
        self.setWindowTitle("test")
        self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)        
        self.setViewportUpdateMode(QtGui.QGraphicsView.FullViewportUpdate)
        #print self.viewportUpdateMode()

    def keyPressEvent(self, event):
        key = event.key()
        if key == QtCore.Qt.Key_Plus:
            self.scaleView(1.2)
        elif key == QtCore.Qt.Key_Minus:
            self.scaleView(1 / 1.2)
        else:
            super(GraphWidget, self).keyPressEvent(event)

    def wheelEvent(self, event):
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.scaleView(math.pow(2.0, -event.delta() / 240.0))

    def drawBackground(self, painter, rect):
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        pen = QtGui.QPen(QtCore.Qt.black, 2/self.sFactor, QtCore.Qt.SolidLine)
        painter.setPen(pen)
        line=painter.drawLine(0, 0, 300, 200)

    def mouseReleaseEvent(self, event):
        #self.update()
        #self.viewport().repaint()
        self.viewport().update()
        #self.scaleView(1.2)
        super(GraphWidget, self).mouseReleaseEvent(event)

    def scaleView(self, scaleFactor):
        self.sFactor = self.matrix().scale(scaleFactor, scaleFactor).mapRect(QtCore.QRectF(0, 0, 1, 1)).width()

        if self.sFactor < 0.07 or self.sFactor > 100:
            return
        self.scale(scaleFactor, scaleFactor)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = GraphWidget()
    widget.show()
    sys.exit(app.exec_())

如果你在mousereleaseevent中调用self.scaleView(1.2),则glich会消失,但仅在事件发生时消失。我想这是因为我没有调用正确的重新/更新,但我找不到合适的...

1 个答案:

答案 0 :(得分:1)

请勿更改后台的默认缓存模式 - 如果您的问题已解决,则问题已解决 你删除了这一行:self.setCacheMode(QtGui.QGraphicsView.CacheBackground)