简体   繁体   中英

How to make widgets stack on top of each other using QScrollArea with Vertical layout in PyQt5?

I'm super new to PyQt5 and trying to design a notification panel where the most recent notification should be placed on top rather than the bottom. For notification I'm using QLabel widget and for notification panel, I'm using a QScrollArea with vertical layout and vertical policy set to Fixed since otherwise it places the label in the center rather than top.

So, the problem is, it is placing my new labels on the bottom when I want to place new ones on the top. I tried to mess with the geometry function, by creating a list to append each new notification label and then traverse the list from highest index to lowest, changing each label's y-axis value accordingly. Here's the code for that:

        if len(self.alert_labels_list) > 0:
            loop_ran = 0
            for l_index in range(len(self.alert_labels_list), 0, -1):
                temp_label = self.alert_labels_list[l_index-1]
                new_ay = self.label_height + 31    # 31 is the y pos for first label while label height is self defined variable that contains the set height which in this case is 80. 
                self.label_height = new_ay
                temp_label.setGeometry(11, new_ay, 430, 80)


        self.x_label.setGeometry(11, 31, 430, 80) # x_label is the new label being added.

        self.label_height = 80

        [...]
        # code which sets the label
        [...]

        self.alert_labels_list.append(self.x_label)

The idea here is that starting from the highest index we'll encounter the most recent labels (alerts) and by adding the (fixed, defined) label height to the y position of prev label we'll make all labels appear in a recent order. I hope it makes sense. Anyway this logic above still doesn't work, maybe because the layout is not letting me customize the position of new widgets being added to it or something?

If you can guide me how can tackle this issue, I'd be more than grateful to you! Thanks!

Huge thanks to @musicamante, his comment contains the answer. I'll just quote him here, " ...if you're using a box layout and want to insert widgets at the "beginning", use layout.insertWidget(0, widget) "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM