QScrollArea变大而不是滚动
我有一个 QScrollArea
,我打算在里面添加一些其他的控件。我希望的是,当里面的控件超出它的大小时,QScrollArea
能够开始滚动。
但是相反的是,滚动区域自己开始变大了。
这是我用的代码:
import sys
from PyQt4 import QtGui, QtCore
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.vbox = QtGui.QVBoxLayout()
self.setLayout(self.vbox)
def add_button(self):
tmp = QtGui.QPushButton("...", self)
self.vbox.addWidget(tmp)
class ScrollArea(QtGui.QScrollArea):
def __init__(self, parent=None):
QtGui.QScrollArea.__init__(self, parent)
self.vbox = QtGui.QVBoxLayout()
self.w = Widget(self)
self.setWidget(self.w) #set the widget to provide scrolling for here
self.vbox.addWidget(self.w)
self.plus = QtGui.QPushButton("button", self)
self.connect(self.plus, QtCore.SIGNAL("clicked()"), self.add_button)
self.vbox.addWidget(self.plus)
self.setLayout(self.vbox)
def add_button(self):
self.w.add_button()
app = QtGui.QApplication(sys.argv)
main = ScrollArea()
main.show()
sys.exit(app.exec_())
我还尝试过在 ScrollArea
类里设置子控件 self.w
的布局,而不是在它自己的类里,但效果还是一样。
1 个回答
1
正如Bakuriu所提到的,使用QScrollArea
时,重要的是不要给它自己设置布局,而是通过setWidget
方法指定一个小部件(下面用w
表示),让这个滚动区域来管理。
在调用setWidget
之前,一定要先设置w
的布局。如果你想在w
里面添加多个其他小部件(比如上面问题中的QPushButton
),那么也要记得为w
的布局调用setSizeConstraint
(例如,setSizeConstraint(QLayout.SetMinAndMaxSize)
,更多选项可以查看这个链接)。想了解QScrollArea
的更多细节,可以访问这个链接。
下面的代码是一个可运行的示例:
import sys
from PyQt4 import QtGui, QtCore
class Widget(QtGui.QWidget):
""" Here we add more buttons, if the size of the buttons exceeds the size of the widget scrolling starts. """
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.vbox = QtGui.QVBoxLayout()
self.vbox.setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize)
self.setLayout(self.vbox)
def add_button(self):
tmp = QtGui.QPushButton("...", self)
self.vbox.addWidget(tmp)
class ScrollArea(QtGui.QScrollArea):
""" This scroll area only handles one widget for which scrolling should be provided. """
def __init__(self, parent=None):
QtGui.QScrollArea.__init__(self, parent)
self.w = Widget()
self.setWidget(self.w) #set the widget to provide scrolling for here
def add_button(self):
self.w.add_button()
class MainWindow(QtGui.QWidget):
""" Use this widget to arrange the QScrollArea and the QPushButton. """
def __init__(self, parent=None):
QtGui.QWidget.__init__(self)
self.vbox = QtGui.QVBoxLayout()
self.scroll = ScrollArea(self)
self.vbox.addWidget(self.scroll)
self.plus = QtGui.QPushButton("button", self)
self.connect(self.plus, QtCore.SIGNAL("clicked()"), self.add_button)
self.vbox.addWidget(self.plus)
self.setLayout(self.vbox)
def add_button(self):
self.scroll.add_button()
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())