自动调整 QLabel 的大小以适应更新后的 QTableWidget 跨度

Auto resize QLabel to fit updated QTableWidget span

我有一个 QTableWidget,还有一个 QLabel,我使用 .setCellWidget() 将其放入 table 的单元格中。 在 运行 期间,我使用 .setSpan()

更改 QLabel 所在的 QTableWidget 单元格的跨度

但是当我更改 QLabel 所在的单元格的跨度时,QLabel 不会调整大小。

下面是一些代码和截图:

def generate_table(self):
    global gtable
    
    table = QTableWidget(20, 60)
    gtable = table
    
    def create_task(self):
    task_widget = QWidget()
    task_layout = QHBoxLayout()
    task_widget.setLayout(task_layout)
    
    task = QLabelClickable(the_task_name)
    
    task_layout.addWidget(task)
    
    gtable.setCellWidget(selected_row_column[0], selected_row_column[1], task_widget)
    
    // if I include this part of the code, everything looks fine, both cell, widget and label scale properly, as visible through background color, below line is not the problem, notice its in the same function as where I set the cell widget

    the_duration = 3    

    gtable.setSpan(selected_row, selected_column, 1, the_duration)
    
    // Below is how I change the cell span. The rrow and ccolumn are integers, basically just cell coordinates
    def save_task(self):
    gtable.setSpan(rrow, ccolumn, 1, w_dr.value())

(到处都是大量代码,所以我包含了我认为相关的代码,让我知道我应该包含代码的其他部分)

它应该是这样的:(这是第一个跨度更改行所做的)

这是它的样子:(这是最后一行的作用)

我的问题是,如何调整 QLabel / QWidget 的大小以自动适应单元格的更新大小?

您可以看到第一个跨度是正确的,因为它应用在将更新视图几何图形的同一事件循环中。

跨越不会自动执行此操作(这可能是一个错误),因此解决方案是使用 updateGeometries(),其中:

Updates the geometry of the child widgets of the view.

这意味着视图的所有 小部件将正确调整大小和更新,包括滚动条和单元格小部件。

    def save_task(self):
        gtable.setSpan(rrow, ccolumn, 1, w_dr.value())
        gtable.updateGeometries()

一个非常重要的建议:避免使用全局变量,它们并不像人们想象的那样好用,而且实际上经常会导致难以解决的问题和错误追踪;改用实例成员(例如 self.gtable)。