简体   繁体   English

PyQt5 - 如何在没有布局的情况下将小部件动态添加到 window

[英]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.我一直在尝试解决这个问题,我不想使用布局的原因是因为小部件在调整大小时会随 window 缩放,我希望它们保持原样,我已经做到了我可以拖放的地方小部件,但由于它们处于布局中,所以它搞砸了,请有人帮我解决这个问题。

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.我希望能够添加一个 label 小部件,我想将它放在我可以按下按钮的地方,它将在我的 window 中创建一个新的 label 小部件,但我已经可以添加这部分了没有布局的小部件。

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:您只需将另一个属于 window(或 window 本身)的小部件设置为父小部件,并使用 show 方法使其可见:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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