代码之家  ›  专栏  ›  技术社区  ›  voiDnyx

如何将滚动条添加到带有绘制线条的小部件?

  •  1
  • voiDnyx  · 技术社区  · 9 年前

    我很难按我想要的方式工作。我想在彼此下方画一些线,并在一个有滚动条的窗口中显示。

    到目前为止,我可以画线并显示它们,但我的滚动条无法工作。正确的方法是什么?

    文件y.list包含简单的数字对作为行的起点和终点。例如:

    1 100
    4 64
    72 98
    

    这是我迄今为止的代码:

    import sys
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    
    class Example(QWidget):
    
        def __init__(self):
            super(Example, self).__init__()         
    
        def paintEvent(self, e):
    
            qp = QPainter()
            qp.begin(self)
            self.drawLines(qp)
            qp.end()
    
        def drawLines(self, qp):
    
            wTotal = 4*2*117
    
            pen = QPen(QColor(100, 200, 0), 5, Qt.SolidLine)
            qp.setPen(pen)
            qp.drawLine(24, 20, 24+wTotal, 20)
    
            pen = QPen(QColor(0, 0, 255), 2, Qt.SolidLine)
            qp.setPen(pen)
            qp.drawLine(24+wTotal/2,18,24+wTotal/2,22)
    
            pen = QPen(QColor(0, 50, 255), 2, Qt.SolidLine)
            qp.setPen(pen)
    
            with open("y.list", 'r') as points:
    
                linecount = 0
                for line in points:
    
                    linecount += 1
                    splitLine = line.split()
    
                    start = int(splitLine[0])*4
                    end = int(splitLine[1])*4
    
                    qp.drawLine(20+start, 20+5*linecount, 20+end, 20+5*linecount)
    
    
    class Widget(QWidget):
    
        def __init__(self, parent= None):
            super(Widget, self).__init__()
    
            self.setGeometry(200,100,1100,800)
            #Container Widget        
            widget = QWidget()
            #Layout of Container Widget
            layout = QVBoxLayout(self)
            lines = Example()
            layout.addWidget(lines)
            widget.setLayout(layout)
    
            #Scroll Area Properties
            scroll = QScrollArea()
            scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            scroll.setWidgetResizable(True)
            scroll.setWidget(widget)
    
            #Scroll Area Layer add 
            vLayout = QVBoxLayout(self)
            vLayout.addWidget(scroll)
            self.setLayout(vLayout)
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
    
        dialog = Widget()
        dialog.show()
    
        app.exec_()
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   ekhumoro    9 年前

    目前,您已经调整了小部件的大小,因此小部件将自动调整大小以适应可用空间,并且滚动条永远不会改变(因为它们不需要)。

    要改变这一点,您需要给小部件一个特定的大小,并且不要自动调整大小:

        scroll.setWidgetResizable(False)
        scroll.setWidget(widget)
        widget.resize(2000, 2000)
    

    注意:不要试图在绘制事件期间以编程方式调整小部件的大小,因为调整大小本身会导致重新绘制。