如何在 PyQt5 中保持行和列大小与网格布局相同?

     2023-03-25     301

关键词:

【中文标题】如何在 PyQt5 中保持行和列大小与网格布局相同?【英文标题】:How can I keep row and column size the same with the grid layout in PyQt5? 【发布时间】:2021-11-20 22:20:38 【问题描述】:

我正在尝试为国际象棋游戏创建 GUI。我正在使用网格布局,当主窗口打开时,我拥有的标签大小正确。但是,当我调整窗口大小时,网格布局确实会随着窗口移动,但其内容不对齐,并且行和列大小不再匹配。有没有办法让网格布局中的单元格大小始终是正方形(所以行大小=列大小)。

行大小 = 列大小的正确比例:

不正确的比例示例,其中行大小不等于列大小:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setGeometry(500,150,860,860)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        #Adding Grid Layout to the main widget
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout.setHorizontalSpacing(0)
        self.gridLayout.setVerticalSpacing(0)
        
        all_position_labels = []
        
        colour = False
        for x in range(8):
            row = []
            
            for y in range(8):
                #Creating the labels
                self.position = QtWidgets.QLabel(self.centralwidget)
                self.position.setText("Place " + str(x) + " " + str(y))
                if colour == True:
                    self.position.setStyleSheet("border: 0.1em solid black; background: gray;")
                    colour = False
                else:
                    self.position.setStyleSheet("border: 0.1em solid black;")
                    colour = True
                #Adding labels to the GridLayout                
                self.gridLayout.addWidget(self.position, x, y, 1, 1)
                

                row.append(self.position)
            all_position_labels.append(row)   

            if colour == True:
                colour = False
            else:
                colour = True
        del row
        

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 20))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

谢谢。

【问题讨论】:

【参考方案1】:

标签的大小取决于容器的大小,因此可能的解决方案是根据窗口大小调整小部件的大小。

from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import (
    QApplication,
    QGridLayout,
    QLabel,
    QMainWindow,
    QStyle,
    QWidget,
)


class CentralWidget(QWidget):
    def __init__(self, widget):
        super().__init__()
        self._widget = widget
        self.widget.setParent(self)

    @property
    def widget(self):
        return self._widget

    def resizeEvent(self, event):
        super().resizeEvent(event)
        size = min(self.width(), self.height())
        r = QStyle.alignedRect(
            Qt.LeftToRight, Qt.AlignCenter, QSize(size, size), self.rect()
        )
        self.widget.setGeometry(r)


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        container = QWidget()
        central_widget = CentralWidget(container)
        self.setCentralWidget(central_widget)

        lay = QGridLayout(container)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        colour = False
        for i in range(8):
            for j in range(8):
                label = QLabel(f"Place i j", alignment=Qt.AlignCenter)
                label.setStyleSheet(
                    "border: 0.1em solid black;"
                    if colour
                    else "border: 0.1em solid black; background: gray;"
                )
                lay.addWidget(label, i, j)
                colour = not colour
            colour = not colour


def main():
    app = QApplication([])
    app.setStyle("fusion")
    view = MainWindow()
    view.resize(860, 860)
    view.show()
    app.exec_()


if __name__ == "__main__":
    main()

【讨论】:

【pyqt】网格布局qgridlayout

...部件也可能占用多个单元格。如果这做,QGridLayout将猜测如何在列/行上分配大小(基于拉伸因子)。使用removeWidget()可以从布局中删除控件。或者在控件上使用hide()也可以有效地将其隐藏,直到使用show()。上图中第0、2和4列均由... 查看详情

我们如何在 ext js 4.2 中突出显示网格面板的行和列?

】我们如何在extjs4.2中突出显示网格面板的行和列?【英文标题】:howcanwehighlighttherowandcolumnofthegridpanelinextjs4.2?【发布时间】:2015-01-0819:00:12【问题描述】:我们如何在选择网格面板时突出显示当前行和列?我可以突出显示行而... 查看详情

如何在 MVC 应用程序中转置 Kendo UI 网格中的行和列?

】如何在MVC应用程序中转置KendoUI网格中的行和列?【英文标题】:HowtotransposerowsandcolumnsinaKendoUIgridinMVCapplication?【发布时间】:2015-12-2800:08:06【问题描述】:我在我的MVC应用程序中使用KendoUiGrid。我希望在我的网格中显示多个国... 查看详情

Swing 布局 - 在保持组件尺寸的同时使用网格

...题描述】:我想为应用程序制作一个登录栏,但我不知道如何组织一系列JLabel和JTextField,以便它们在水平网格中组织没有这些相同调整大小以适应每个单元格的组件。我还想确保组件组的大小不会调整到某个宽度以下。如何实 查看详情

如何从数据网格中获取行和列

】如何从数据网格中获取行和列【英文标题】:Howtogetrowandcolumnfromdatagrid【发布时间】:2021-09-2712:08:46【问题描述】:我有以下代码,importReactfrom\'react\'importButtonfrom\'@material-ui/core/Button\';importCheckboxfrom\'@material-ui/core/Checkbox\';import... 查看详情

如何在 CSS 网格布局中保持内容居中?

】如何在CSS网格布局中保持内容居中?【英文标题】:HowdoIkeepcontentcenteredinCSSGridLayout?【发布时间】:2019-10-3008:37:33【问题描述】:使用CSS网格布局,我创建了一个网站,其布局会随着屏幕大小而略有变化。在这里,为了将内容... 查看详情

如何从 WPF 中网格内的标签中获取行和列信息?

】如何从WPF中网格内的标签中获取行和列信息?【英文标题】:HowtograbrowandcolumninfofromalabelinsideagridinWPF?【发布时间】:2011-06-3022:10:31【问题描述】:我有一个3x3网格,用作井字游戏的游戏板。每个网格都有一个标签,可以显示... 查看详情

异构网格布局

...行和列。在这里我选择了一个按钮,以便您可以看到它是如何超出边界的:这里是相关的xml代码:https://gist.github. 查看详情

在网格中制作一个矩形图例,带有标记的行和列

】在网格中制作一个矩形图例,带有标记的行和列【英文标题】:Makearectangularlegend,withrowsandcolumnslabeled,ingrid【发布时间】:2013-12-0609:57:13【问题描述】:我有一个ggplot,我在其中将因子映射到填充和alpha,如下所示:set.seed(47)the... 查看详情

使用 ggarrange 添加行和列标题

】使用ggarrange添加行和列标题【英文标题】:addrowandcolumntitleswithggarrange【发布时间】:2020-06-0609:51:21【问题描述】:我有一个ggplots列表,这些ggplots可能过于复杂而无法使用facet_wrap进行排列。所有地块必须共享相同的图例,并... 查看详情

UICollectionViewFlowLayout 的行和列

】UICollectionViewFlowLayout的行和列【英文标题】:RowsandcolumnsofUICollectionViewFlowLayout【发布时间】:2013-03-2919:50:49【问题描述】:给定一个带有流式布局的UICollectionView,计算集合视图的列数(垂直方向)或行数(水平方向)的最简单... 查看详情

grid布局(代码片段)

...上代码section为容器、div为项目(项目不包括p标签)-->行和列 容器里面的水平区域称为"行",垂直区域称为"列"。行和列的交叉区域,称为"单元格"。划分网格的线,称为"网格线"。水平网格线划分出行,垂直网格线划分出... 查看详情

如何通过单击pyqt5中的按钮来制作qlineedit的动态行和列?

】如何通过单击pyqt5中的按钮来制作qlineedit的动态行和列?【英文标题】:Howtomakedynamicrowandcolumnsofqlineeditonaclickofpushbuttoninpyqt5?【发布时间】:2019-09-1420:53:05【问题描述】:我正在开发一个库存管理软件项目,其中我有一小部分... 查看详情

如何在显示网格中使用偏移量(边距)

】如何在显示网格中使用偏移量(边距)【英文标题】:Howtouseoffset(margin)withdisplaygrid【发布时间】:2020-11-0411:23:16【问题描述】:好吧,是时候在CSS中使用带有display:grid的新布局方法了。我尝试在我的CSS库中使用网格,为了与... 查看详情

在引导组件中使用行和列时出现破折号布局问题

】在引导组件中使用行和列时出现破折号布局问题【英文标题】:DashlayoutissuewhenusingRowsandColumsinBootstrapComponents【发布时间】:2021-12-1804:30:09【问题描述】:我正在尝试创建一个简单的仪表板布局,但无法使其正常工作。它涉及... 查看详情

刷新与调整浏览器窗口大小时网格布局呈现不同

】刷新与调整浏览器窗口大小时网格布局呈现不同【英文标题】:Gridlayoutrendereddifferentlyonrefreshvs.resizingbrowserwindow【发布时间】:2021-06-0819:57:41【问题描述】:我刚开始使用网格布局,并注意到它在相同的视口大小上呈现不同:(... 查看详情

grid布局

...通过grid-template-columns和grid-template-rows属性来定义网格中的行和列。这些属性定义了网格的轨道。一个网格轨道就是网格中任意两条线之间的空间。//几种写法g 查看详情

如何获取 javascript 中用于 flexbox 和网格布局的行数和列数?

】如何获取javascript中用于flexbox和网格布局的行数和列数?【英文标题】:Howtogetcountofrowsandcolumnsinjavascriptforflexboxandgridlayout?【发布时间】:2018-09-0511:30:12【问题描述】:这样的弹性盒:display:flex;flex-flow:rowwrap;和这样的网格:disp... 查看详情