如何在QTableView中按比例调整列宽?

2024-04-25 04:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按比例更改QTableView小部件中所有列的列宽,这样无论数据如何,每个列都具有相同的宽度。例如,如果一个表有三列,则每列的宽度应始终为可用水平空间的三分之一,并且当用户调整对话框大小时,宽度应自动更新。在

到目前为止,我只能根据内容调整列的大小,这不是我想要的。以下是我目前掌握的代码:

主界面

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>624</width>
    <height>329</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QTableView" name="tableView">
       <property name="alternatingRowColors">
        <bool>true</bool>
       </property>
       <property name="selectionBehavior">
        <enum>QAbstractItemView::SelectRows</enum>
       </property>
      </widget>
     </item>
     <item>
      <layout class="QVBoxLayout" name="verticalLayout_2">
       <item>
        <widget class="QPushButton" name="btnPopulate">
         <property name="text">
          <string>Populate</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <tabstops>
  <tabstop>btnPopulate</tabstop>
 </tabstops>
 <resources/>
 <connections/>
</ui>

测试.py

^{pr2}$

我有以下问题:

  1. 如何更改代码以按比例调整列宽?在
  2. 为什么setWordWrap(True)不换行?在

Tags: 代码namerectuistring宽度versionproperty
1条回答
网友
1楼 · 发布于 2024-04-25 04:39:13

这可以通过setting the section resize mode来实现。要获得相等的列宽:

self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

垂直包装内容:

^{pr2}$

不需要调用resizeToContentssetWordWrap或{}。调用setWordWrap(False)将切换到省略右边的文本,而不是换行。在

请注意,由于行/列大小调整是自动完成的,因此用户或编程人员无法再更改大小。在

相关问题 更多 >