Simplify my code, one function to create is used b

2019-09-19 23:36发布

问题:

I have this code:

class Main(QWidget):
    def __init__(self):
        super().__init__()
        self.init_gui()

    def init_gui(self):
        self.layout_main = QVBoxLayout()
        self.setLayout(self.layout_main)

        self.first()
        self.second()

        self.showMaximized()

    def scroll_areas(self):
        scroll_area = QScrollArea(self)
        widget = QWidget()
        layout = QVBoxLayout()

        scroll_area.setWidgetResizable(True)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setFixedSize(200, 200)
        widget.setLayout(layout)
        scroll_area.setWidget(widget)
        # self.layout_main.addLayout(layout)

    def first(self):
        title = QLabel("<h1>First</h1>")
        title.setTextFormat(Qt.RichText)


    def second(self):
        title = QLabel("<h1>Second</h1>")
        title.setTextFormat(Qt.RichText)

I would like to have function scroll_areas in functions first and second and then I would like something like this:

add QLabel title to scroll_areas's layout

I the last thing is adding scroll_areas's layout to main layout, I commented the line in scroll_areas, cuz it has to be in last line in first and second.

Thanks!

回答1:

Try it:

class Main(QWidget):
    def __init__(self):
        super().__init__()
        self.init_gui()

    def init_gui(self):
        self.layout_main = QVBoxLayout()
        self.setLayout(self.layout_main)

        self.scroll_areas()                                          # +++

        self.first()
        self.second()

        self.showMaximized()

    def scroll_areas(self):
        scroll_area = QScrollArea(self)
        widget = QWidget()
        self.layout = QVBoxLayout()

        scroll_area.setWidgetResizable(True)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setFixedSize(200, 200)
        widget.setLayout(self.layout)
        scroll_area.setWidget(widget)

        # self.layout_main.addLayout(layout)
        self.layout_main.addWidget(scroll_area)                       # +++

    def first(self):
        title = QLabel("<h1>First</h1>")
        title.setTextFormat(Qt.RichText)
        self.layout.addWidget(title)                                  # +++

    def second(self):
        title = QLabel("<h1>Second</h1>")
        title.setTextFormat(Qt.RichText)
        self.layout.addWidget(title)                                  # +++