Qlab在QGridLayout前面

时间:2018-02-22 20:22:59

标签: python qt pyqt pyqt5

我正在尝试QLabel显示超过 a 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_())

产生以下输出:

enter image description here

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

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

这样的事情:

enter image description here

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

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

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class Foo(QWidget):
    sizeChanged = pyqtSignal(QSize)
    def __init__(self):
        super().__init__()
        grid_layout = QGridLayout(self)

        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)

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

        self.sizeChanged.connect(red_label.resize)
        self.show()

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

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

enter image description here

答案 1 :(得分:1)

这可能是一个不太优雅的解决方案,但它确实将红色标记为居中,因为窗口已调整大小。

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

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