QGridLayout 前面的 Qlabel

Qlabel in front of a QGridLayout

我正在尝试让 QLabel 出现 而不是 QGridLayout,但我不知道该怎么做。

这是示例代码:

from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QFrame, QLabel
import sys

class Foo(QWidget):

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



        grid_layout = QGridLayout()

        rect1 = QLabel('RECT1')
        rect1.setStyleSheet("color: green;")
        grid_layout.addWidget(rect1, 0, 1)

        rect2 = QLabel('RECT2')
        rect2.setStyleSheet("color: blue;")
        grid_layout.addWidget(rect2, 0, 2)

        self.setLayout(grid_layout)
        self.show()

app = QApplication(sys.argv)
foo = Foo()
sys.exit(app.exec_())

产生以下输出:

例如,我想创建另一个红色的 QLabel,并将其显示在图像的中央:

red_label = QLabel('red')
red_labe.setStyleSheet("font-size:20pt; color: red;");

像这样:

我怎样才能做到这一点?

一个可能的解决方案是使 red_label 成为 QWidget 的子对象,因为您必须在创建对象时传递 self 参数。除此之外,QLabel 必须在 window 发生时更改大小,为其模拟布局任务将创建一个将在 resizeEvent 事件中发出的信号:

import sys

from PyQt5 import QtCore, QtWidgets


class Foo(QtWidgets.QWidget):
    sizeChanged = QtCore.pyqtSignal(QtCore.QSize)

    def __init__(self):
        super().__init__()
        grid_layout = QtWidgets.QGridLayout(self)

        rect1 = QtWidgets.QLabel("RECT1")
        rect1.setStyleSheet("color: green;")
        grid_layout.addWidget(rect1, 0, 1)

        rect2 = QtWidgets.QLabel("RECT2")
        rect2.setStyleSheet("color: blue;")
        grid_layout.addWidget(rect2, 0, 2)

        red_label = QtWidgets.QLabel("red", self)
        red_label.setAlignment(QtCore.Qt.AlignCenter)
        red_label.setStyleSheet("font-size: 20pt; color: red;")

        self.sizeChanged.connect(red_label.resize)

    def resizeEvent(self, event):
        self.sizeChanged.emit(event.size())
        super().resizeEvent(event)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    foo = Foo()
    foo.show()
    sys.exit(app.exec_())

这可能是一个不太优雅的解决方案,但它确实在 window 调整大小时使红色标记居中。

class Foo(QWidget):

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


        grid_layout = QGridLayout()

        rect1 = QLabel('RECT1')
        rect1.setStyleSheet("color: green;")
        grid_layout.addWidget(rect1, 0, 0)

        rect2 = QLabel('RECT2')
        rect2.setStyleSheet("color: blue;")
        grid_layout.addWidget(rect2, 0, 2)


        grid_layout_two = QGridLayout()

        blank_label = QLabel()

        red_label = QLabel('red')
        red_label.setStyleSheet("font-size:20pt; color: red;")
        grid_layout_two.addWidget(blank_label, 0, 0)
        grid_layout_two.addWidget(red_label, 0, 1)
        grid_layout_two.addWidget(blank_label, 0, 2)

        grid_layout_three = QGridLayout()
        grid_layout_three.addItem(grid_layout, 0, 0)
        grid_layout_three.addItem(grid_layout_two, 0, 0)

        self.setLayout(grid_layout_three)
        self.show()

app = QApplication(sys.argv)
foo = Foo()
sys.exit(app.exec_())

基本上制作三个网格布局,定位元素,使红色标签位于其他两个标签的中心,但在其他标签布局前面的网格布局中。