Issue
I've just starting to learn/use PyQt for my internship and am having some issues finding out how to add a scroll bar to this simple program:
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300,300,180,100)
self.button1= QPushButton(self)
self.button1.setText("Button 1")
self.button1.move(10,10)
self.button2= QPushButton(self)
self.button2.setText("Button 2")
self.button2.move(150,10)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Essentially, the window has a set size (here it's 180x100) but has elements outside of that size (i.e. button2 extents from 150 to 220 which makes it half outside of the 180px window)
Click-dragging the window larger shows the entirety of button2, which is fine, but I need a way to keep the window the size it is and just have a scroll bar to see all of the unseen items.
Solution
The QScrollArea
class provides a scrolling view onto another widget.
More... https://doc.qt.io/qt-5/qscrollarea.html
A scroll area is used to display the contents of a child widget within a frame.
If the widget exceeds the size of the frame, the view can provide scroll bars so
that the entire area of the child widget can be viewed.
The child widget must be specified with setWidget()
.
import sys
from PyQt5.Qt import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 180, 100)
self.scroll = QScrollArea()
self.widget = QWidget()
self.widget.resize(280, 200)
self.scroll.setWidget(self.widget)
self.button1= QPushButton(self.widget)
self.button1.setText("Button 1")
self.button1.move(10, 10)
self.button2= QPushButton(self.widget)
self.button2.setText("Button 2")
self.button2.move(150, 10)
self.setCentralWidget(self.scroll)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Answered By - S. Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.