QTableView 将小部件缩小为内容 [英] QTableView shrink widget to content

查看:88
本文介绍了QTableView 将小部件缩小为内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 QTableView 来显示一些数据.到目前为止,这有效.有一行,单击该行时,会出现一些隐藏的行.单击另一行将隐藏所有其他行.一排:

I use a QTableView to show some data. This works so far. There is one row and when clicking into this row, some hidden rows occure. Click into an other row will then hide all others. One row:

多行:

但是我怎样才能去除周围的空白?将 strech() 添加到 QVBoxLayout 会产生一个半白半灰的窗口,如图所示.resizeRowsToContents() 也不起作用.添加间隔也没有效果.

But how can i remove the white space around? Adding strech() to the QVBoxLayout yields in a half white and a half grey window as shown in the pictutre. resizeRowsToContents() also does not work. Adding spacers also have no effect.

我想要的是,窗口保持大小,空白减少到最小(如外部单元格边框).所以单元格将有一个白色的背景,其余的应该是灰色的.是否有某种拉伸"?也在表格视图里面?展开或折叠表格后,周围也不应有空白.

What I want to have is, that the Window keeps the size and the white space is reduced to it's minimum (like the outer cell borders). So the cells will have a white background, the rest should be grey. Is there some kind of "strech" also inside the table view? After expanding or collapsing the table, there should be also no white space around.

我的代码,你可以使用:

My code, which you can use:

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


data = [['a','b','c','x','y'],['d','e','f','x','y'],['g','h','i','x','y']]

class TableModel(QAbstractTableModel):
    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole:
            # See below for the nested-list data structure.
            # .row() indexes into the outer list,
            # .column() indexes into the sub-list
            return self._data[index.row()][index.column()]

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            row = index.row()
            column = index.column()
            self._data[row][column] = value
            self.dataChanged.emit(index, index)
            return True
        return QAbstractTableModel.setData(self, index, value, role)

    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.selection = data[0]
        # buil UI
        self.init_ui()

    def init_ui(self):
        # layout
        self.box_window = QVBoxLayout()
        # content
        self.invisible_table = QTableView()
        tmp = copy.deepcopy(data)
        tmp.insert(0,self.selection)
        self.model = TableModel(tmp)
        self.invisible_table.setModel(self.model)
        self.invisible_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.invisible_table.horizontalHeader().hide()
        self.invisible_table.horizontalHeader().setMinimumSectionSize(100)
        self.invisible_table.verticalHeader().hide()
        # self.invisible_table.hide()
        for i in range(1,self.model.rowCount(0)):
            self.invisible_table.setRowHidden(i,True)
        self.invisible_table.doubleClicked.connect(self.clicked)
        self.invisible_table.clicked.connect(self.clicked)
        self.invisible_table.setMinimumSize(1,1)
        self.invisible_table.resizeColumnsToContents()
        self.invisible_table.resizeRowsToContents()

        # self.box_window.addLayout(self.visible_line)
        self.box_window.addWidget(self.invisible_table)
        self.box_window.addStretch()
        # build central widget and select it
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.centralWidget().setLayout(self.box_window)

        # show window
        self.setGeometry(50,50,1024,768)
        self.setWindowTitle("Test")
        self.show()

    def popup(self, widget):
        print("popup")
        print(widget)
        self.invisible_table.show()

    def clicked(self, qmi):
        print("clicked")
        rowIndex = qmi.row()
        if rowIndex == 0:
            for i in range(1,self.model.rowCount(0)):
                if self.invisible_table.isRowHidden(i):
                    self.invisible_table.setRowHidden(i,False)
                else:
                    self.invisible_table.setRowHidden(i,True)
        else:
            self.selection = data[rowIndex-1]
            print(self.selection)
            col = 0
            for d in self.selection:
                # self.model._data[0][col]=d
                self.model.setData(self.model.index(0,col),d)
                col += 1
            for i in range(1,self.model.rowCount(0)):
                self.invisible_table.setRowHidden(i,True)

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

:根据要求,我想要实现的编辑图像:

: As requested, an edited image of what I want to achieve:

:这就是现在的样子.在右侧,应该有这个下拉列表"(伪组合框)

: This is, how it looks like in the moment. On the right side, there should be this "drop down list" (pseudo-combobox) previous approach

推荐答案

我自己解决了这个问题.

I solved this issue by myself.

解决办法是:

  • 表格最小尺寸必须设置为一个足够大的值,因此减小窗口不会缩小表格
  • 表格最大尺寸必须设置为最小值,这样就不会裁剪表格

要达到这两者,可以使用函数 setFixedSize().并且必须通过迭代列和行并汇总所有列宽/行高来计算值(宽度和高度).唯一要记住的是:当桌子周围有框架时,还必须添加边框线粗细.

To reach both, the function setFixedSize() can be used. And the values (width and height) must be computed by iterating through the columns and rows and summarizing up all column widths/row heights. Only thing to keep in mind: When there is a frame around the table, the border line thickness has to be added also.

每次更改表格布局后都必须设置大小(隐藏/显示行/列、添加/删除行/列、添加/隐藏标题等)

setting the size has to be done everytime after changing the table layout (hide/show rows/columns, add/remove rows/columns, add/hide header and so on)

# determine width and height
table_width = 0
table_height = 0
for i in range(table.columnCount()):
    table_width += table.columnWidth(i)
for i in range(table.rowCount()):
    table_height += table.rowHeight(i)
if not table.horizontalHeader().isHidden():
    table_height += table.horizontalHeader().height()
table.verticalHeader().hide()
table.setFrameStyle(QFrame.NoFrame)
table.setFixedSize(table_width,table_height)

结果:

这篇关于QTableView 将小部件缩小为内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆