QTableView issue with resizeEvent()

QTableView issue with resizeEvent()

本文关键字:resizeEvent with issue QTableView      更新时间:2023-10-16

我有一个对象,它继承了QTableView,并重写resizeEvent()方法,以便在调整整个表的大小时,将表列的宽度设置为可用空间的百分比。

代码如下:

void DDUTableView::resizeEvent(QResizeEvent* ev)
{
  int num_columns = NUM_ELEMENTS(COLUMN_WIDTHS);
  if (num_columns > 0) {
    int width = ev->size().width();
    int used_width = 0;
    // Set our widths to be a percentage of the available width
    for (int i = 0; i < num_columns - 1; i++) {
        int column_width = (width * COLUMN_WIDTHS[i]) / 100;
        this->setColumnWidth(i, column_width);
        used_width += column_width;
    }
    // Set our last column to the remaining width
    this->setColumnWidth(num_columns - 1, width - used_width);
}
// Call our base resizeEvent to handle the vertical resizing which 
// we don't bother with here
QTableView::resizeEvent(ev);

}

这一切都很好,直到用户手动调整其中一列的大小并将其拉伸到视口之外(打开水平滚动条)。然后,这将触发我的resizeEvent()调用,该调用将列宽重置为默认百分比。

我可以通过连接到表头上的sectionResized()信号并设置计时器来解决这个问题。如果在计时器处于活动状态时调用resizeEvent(),那么我不会重新计算表宽度。

以下代码:

connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(slotSectionResized(int, int, int)));
void DDUTableView::slotSectionResized(int /*logicalIndex*/, int /*oldSize*/, int /*newSize*/)
{
    timer_->start(500);
}

void DDUTableView::resizeEvent(QResizeEvent* ev)
{
if (timer_->isActive()) {
    return;
}
// etc

这很有效,但很混乱。无论如何,简单的问题是,如果用户手动调整列标题超出视口范围,我能阻止resizeEvent()被调用吗?或者,如果没有,是否可以在resizeEvent()中识别是否发生了这种特殊情况,而无需设置计时器等?

检查滚动条是否可见适用于我的场景。

void DDUTableView::resizeEvent(QResizeEvent* ev)
{
    if (!horizontalScrollBar()->isVisible()) {
        int num_columns = NUM_ELEMENTS(COLUMN_WIDTHS);
        if (num_columns > 0) {
            int width = ev->size().width();
            int used_width = 0;
            // Set our widths to be a percentage of the available width
            for (int i = 0; i < num_columns - 1; i++) {
                int column_width = (width * COLUMN_WIDTHS[i]) / 100;
                this->setColumnWidth(i, column_width);
                used_width += column_width;
            }
            // Set our last column to the remaining width
            this->setColumnWidth(num_columns - 1, width - used_width);
        }
    }
    // Call our base resizeEvent to handle the vertical resizing which 
    // we don't bother with here
    QTableView::resizeEvent(ev);

}