简体   繁体   English

如何将按钮移到pyqt5中的另一帧?

[英]how to move button to another frame in pyqt5?

There are two frames contain buttons. 有两个包含按钮的框架。

When does click button in Left frame, clicked button move to right frame. 当在左框架中单击按钮时,单击的按钮移至右框架。

How to move button to another frame in pyqt? 如何将按钮移到pyqt中的另一帧?

def create_widget(self):

    left_frame = QFrame(self)
    left_frame.setFixedWidth(300)
    left_frame.setFixedHeight(400)
    left_frame.move(0, 0)


    for x in range(10):
        btn = QPushButton('button', left_frame)
        btn.setFixedWidth(50)
        btn.setFixedHeight(20)
        btn.move(5, 0+(30*x))
        btn.clicked.connect(self.click_btn_add)


    right_frame = QFrame(self)
    right_frame.setFixedWidth(300)
    right_frame.setFixedHeight(400)
    right_frame.move(400, 0)


def click_btn_add(self):
    # How to move button to another frame?

The position of a widget is relative to the parent, and that is clear since the buttons have as their parent a self.left_frame and their positions are relative to it. 小部件的位置是相对于父级的,这很清楚,因为按钮具有一个self.left_frame作为其父self.left_frame并且它们的位置是相对于它的。 If you want it to move to the other QFrame you just have to set the other parent to the other QFrame with setParent() and make it visible with show() (when changing parent the widget is hidden). 如果您希望它移动到另一个QFrame ,则只需使用setParent()将另一个父级设置为另一个QFrame ,并通过show()使它可见(更改父级时,该小部件将被隐藏)。 To obtain the button in the slot we will use sender() that returns the object that issued the signal, and in this case it is the button. 为了获得插槽中的按钮,我们将使用sender()返回发出信号的对象,在这种情况下,它就是按钮。 In the following I will make that each time you press the button it will move to the other QFrame : 在下文中,我将确保每次您按下按钮时,它将移至另一个QFrame

import sys

from PyQt5.QtWidgets import *

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.create_widget()

    def create_widget(self):
        self.left_frame = QFrame(self)
        self.left_frame.setFixedSize(300, 400)
        self.left_frame.move(0, 0)

        self.right_frame = QFrame(self)
        self.right_frame.setFixedSize(300, 400)
        self.right_frame.move(400, 0)

        for x in range(10):
            btn = QPushButton('button', self.left_frame)
            btn.setFixedSize(50, 20)
            btn.move(5, 30*x)
            btn.clicked.connect(self.click_btn_add)

    def click_btn_add(self):
        btn = self.sender()
        new_parent = self.right_frame if btn.parent() == self.left_frame else self.left_frame
        btn.setParent(new_parent)
        btn.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

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

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