0

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.

  • "I have done this part already" then provide us a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of what you've got so far so that we can understand how to possibly help you. – musicamante Feb 22 '21 at 22:55
  • While the issue can be "simple", we cannot always guess what you're facing. If we ask a question, there's probably a good reason, as "I think it's clear what I'm asking" is very often the complete opposite. You're probably lucky as eyllanesc answer got what you needed, but you should consider that for future reference. We get hundreds of questions each day, we cannot in any way know what is your level of understanding, and we might give you an answer that doesn't fit your needs or you don't understand; we cannot always just "shoot in the dark". If we ask you for a MRE, there are good reasons. – musicamante Feb 22 '21 at 23:11
  • @musicamante I'm so sorry I responded in that way, I had misread the comment and upon noticing my mistake I had deleted my comment, I understand now and I will be sure to take that into consideration next time I go to ask a question, I am really grateful someone was able to help me out as I had spent two full days trying to figure it out on my own, again sorry, I should of noticed my mistake sooner. – kyarnell04 Feb 23 '21 at 06:31

1 Answers1

2

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241