【问题标题】:Is there any way to add dynamicly QPushButton object to QWidget without defining a layout? [duplicate]有没有办法在不定义布局的情况下将 QPushButton 对象动态添加到 QWidget? [复制]
【发布时间】:2019-12-16 15:16:16
【问题描述】:

我正在尝试在不使用布局的情况下在单击事件上添加按钮。 我应该如何定义新的 QPushButtons?

我不使用布局的原因是我不希望按钮按布局排列。 创建新按钮后,我改变了他的位置。 当新按钮添加到布局中时,它会重新排列顺序,包括我已经移开的按钮。

所以,我尝试将一个静态按钮数组添加到小部件的初始化函数中,然后将一个新按钮附加到数组中。 但不幸的是,它没有刷新按钮或只是不显示它们 (我打印了按钮列表中的项目数量,尽管没有显示任何按钮,但它正在增长)。

我的结论是:

1) 尝试禁用 addWidget 功能上的布局固定定位。 或

2) 将按钮添加到按钮数组后刷新小部件。

对于 1. 除了(可能)重新创建我试图避免的自定义布局之外,我找不到解决方案。 和 2. 找不到任何解决方案并尝试了父元素上的 .show 和 .hide 函数

当前两个移开时,这段代码创建了 20 个不同的按钮。

class Ex(QWidget):
    def __init__(self, parent):
        super().__init__()
        self.initUI()
        self.ID = 20

    def initUI(self):
        self.a = [QPushButton(f'btn{i}') for i in range(20)]
        self.a[0].move(55, 55)
        self.a[1].move(88, 88)
        self.a[1].clicked.connect(self.clicked) # I know only this connected to the function..

   def clicked(self):
        self.ID+=1 # defined currectly in the class.
        self.a += [QPushButton(f'btn{self.ID}')] #tried .append(btn) too
        self.a[-1].move(300, 300)
        print(len(self.a)) #prints 21 after one click (on a[1]) and so on...


但是点击激活后最后一个对象没有显示出来。

我希望 clicked 函数将 QPushButton 小部件添加到 Parent 小部件,而不会打乱所有其他 QPushButton 位置。 通过布局修复混乱和显示更改的元素数组都是可以接受的。 任何其他想法也是有福的。

p.s 我已经在整个网络上搜索了一个没有成功的解决方案,尽管很少有帖子几乎接近我所需要的。

【问题讨论】:

    标签: python qt pyqt qt5 pyqt5


    【解决方案1】:

    QPushButton 的第二个参数是父小部件 co,您可以将点击功能更改为:

       def clicked(self):
            self.ID+=1 # defined currectly in the class.
            self.a += [QPushButton(f'btn{self.ID}', self)] #tried .append(btn) too
            self.a[-1].move(300, 300)
            self.a[-1].show()
            print(len(self.a)) #prints 21 after one click (on a[1]) and so on...
    

    然后它应该显示出来。

    更通用。所有 Qt 小部件都有函数setParent co 它可以写成:

       def clicked(self):
            self.ID+=1 # defined currectly in the class.
            self.a += [QPushButton(f'btn{self.ID}')] #tried .append(btn) too
            self.a[-1].setParent(self)
            self.a[-1].move(300, 300)
            self.a[-1].show()
            print(len(self.a)) #prints 21 after one click (on a[1]) and so on...
    

    【讨论】:

    • 原行是:python self.a = self.a + [Button(f'Button{self.ID}', self)] 和定义的类:python class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent) 并且它仍然无法正常工作:/
    • 我不明白这条评论。
    • 即使我设置了父元素,它也没有显示元素。 <__main__.ex object at> 我测试了亲子关系,这就是结果。
    • 好的。我知道了。我测试并添加了show() 函数的用法。在我的电脑上它工作。我不确定为什么需要show
    • 是的,突然间它也对我有用。虽然我很确定我试过这个。谢谢大佬!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2012-01-11
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多