简体   繁体   中英

PyQt5 - How to dynamically add widgets to window without layout

I've been trying to figure this one out, the reason I don't want to use a layout is because the widgets scale with the window when resizing and I want them to stay put, I have made it where I can drag and drop the widgets but with them being in a layout it messes it up, please can someone help me figure this out.

I Want to be able to add lets say a label widget, I want to have it where I can press a button and it will create a new label widget in my window, I have done this part already but I want to be able to add widgets without the layout.

You just have to set another widget that is part of the window (or the window itself) as parent and make it visible with the show method:

import random
import sys

from PyQt5 import QtCore, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        button = QtWidgets.QPushButton("Add", self)
        button.clicked.connect(self.handle_clicked)

        self.resize(640, 480)

    def handle_clicked(self):
        pos = QtCore.QPoint(*random.sample(range(400), 2))
        label = QtWidgets.QLabel(self)
        label.move(pos)
        label.setText("{}-{}".format(pos.x(), pos.y()))
        label.show()


def main():
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

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