PyQt5 添加自定义 QWidget 到 QLayout

Max*_*Max 0 python qt pyqt qwidget qlayout

目前我正在尝试将自定义 QWidget 类添加到 QVBoxLayout。我遇到的问题是小部件根本没有出现在布局中。我什至尝试设置 QWidget 的最小大小,因为我认为小部件没有显示,因为它的默认大小设置为零。

这是类的简化:

class myWidget(QWidget):

    def __init__(self):
        super().__init__()

        # Slider
        self.mySlider = QSlider(Qt.Horizontal)
        self.mySlider.setRange(-360, 360)

        # LCD Screen
        self.lcd = QLCDNumber()
        self.lcd.setMinimumHeight(45)
        self.lcd.setMaximumHeight(75)

        # set Size
        self.setMinimumSize(QSize(400,300))
Run Code Online (Sandbox Code Playgroud)

我删除了滑块和 LCD 屏幕之间的信号和插槽,因为我在这里不担心功能。只有我在以下代码中的两个按钮之间直接获得了 QSize(400,300) 的灰色区域:

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        #Create Widgets to be Added to Central Widget
        self.w1 = QPushButton("First")
        self.w2 = myWidget()
        self.w3 = QPushButton("Third")

        #Set Central Widget and VBox
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout()
        self.central_widget.setLayout(self.layout)

        #Add widgets
        self.layout.addWidget(self.w1)
        self.layout.addWidget(self.w2)
        self.layout.addWidget(self.w3)
Run Code Online (Sandbox Code Playgroud)

所以我所做的只是创建 3 个小部件,并将它们放入中央小部件内的 QVBoxLayout 中。2 个按钮小部件w1w3出现,但我的自定义小部件没有出现,并且通过setMinimumSize增加小部件的大小仅在w1和之间添加灰色间距w3

所以小部件在那里它只是由于某种原因不可见。我对 PyQt 很陌生,所以请解释为什么会发生这种情况。

Bre*_*bel 5

QWidgets are just containers for other widgets. A QWidget without any layout and subwidgets will just look like empty space unless you're doing some custom painting or styling.

In your example, you're not actually adding any sub-widgets to your custom widget. In order to add a sub-widget to another widget, you need to either set the parent of the subwidget, or add the subwidget to the layout of the parent widget (which automatically re-parents the subwidget)

class myWidget(QWidget):

    def __init__(self):
        super().__init__()

        # Slider
        self.mySlider = QSlider(Qt.Horizontal)
Run Code Online (Sandbox Code Playgroud)

Here, you are creating a QSlider, but it's not actually owned by MyWidget, it's going to end up being owned by Qt, and I would expect it to be drawn in the upper left hand corner of your main window.

In order to make this a subwidget of MyWidget you need to set the parent and add it to a layout.

class myWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.myLay = QVBoxLayout()
        self.setLayout(self.myLay)

        # Notice self is being passed in to set the parent
        self.mySlider = QSlider(Qt.Horizontal, self)

        # You need to add widgets to a layout to position them properly
        self.myLay.addWidget(self.mySlider)
Run Code Online (Sandbox Code Playgroud)