调整QTableWidget的水平标题以适合内容

问题描述 投票:0回答:1

我正在制作一个需要在QTableWidget中显示CSV文件的应用程序。当前,任何特别长的标题都将被切断。这是一个最小的代码示例:

import os
import sys
import pandas
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QInputDialog, QFileDialog, QTableWidgetItem

class CsvParser(QMainWindow):
    def __init__(self):
        super(CsvParser, self).__init__()
        #Changing basic window properties
        self.setWindowTitle("CSV Parser")
        self.setFixedSize(521, 305)

        #Calling UI function
        self.CsvParserUI()

        #Changing font and text size
        font = QtGui.QFont()
        font.setFamily("Segoe UI")
        font.setPointSize(10)
        self.setFont(font)

    def CsvParserUI(self):
        #QTableWidget for viewing CSV file
        self.csvView = QtWidgets.QTableWidget(self)
        self.csvView.setGeometry(QtCore.QRect(20, 20, 481, 192))
        self.csvView.setObjectName("csvView")
        self.csvView.setColumnCount(0)
        self.csvView.setRowCount(0)

        #Button for opening CSV file
        self.openBtn = QtWidgets.QPushButton(self)
        self.openBtn.setGeometry(QtCore.QRect(200, 240, 121, 41))
        self.openBtn.setText("Open CSV")
        self.openBtn.setObjectName("openBtn")
        self.openBtn.clicked.connect(self.populateTable)

    def populateTable(self):
        file, _ = QFileDialog.getOpenFileName(self, "Open CSV File", os.getcwd())

        #If user chose file
        if file:
            #Setting csvView column and row count according to the size of the file
            self.csvView.setColumnCount(self.getCols(file))
            self.csvView.setRowCount(self.getRows(file))

            pos_dict = self.createPositionDict(file)

            #Here is where the problem lies
            self.csvView.setHorizontalHeaderLabels(["Not Cut off", "This will be cut off"])

            #Appending the CSV data to csvView
            for column, index in enumerate(pos_dict.values()):
                for row, item in enumerate(pandas.read_csv(file, usecols=self.createPositionDict())):
                    self.csvView.setItem(row, column, QTableWidgetItem(str(item)))
        #If user didn't choose file
        else:
            print("No file was selected")

    #Gets number of columns in file
    def getCols(self, file):
        data = pandas.read_csv(file)

        return len(data.columns)

    #Gets number of rows in file
    def getRows(self, file):
        data = pandas.read_csv(file)

        return len(data)

    #Creates a dictionary of indicies that helps later with populating the table
    def createPositionDict(self, file):
        data = pandas.read_csv(file)

        positionDict = {}

        for i, column in enumerate(data.columns):
            payload = {int(i): column}
            positionDict.update(payload)

        return positionDict

def window():
    app = QApplication(sys.argv)
    win = CsvParser()
    win.show()
    sys.exit(app.exec_())

if __name__ in "__main__":
    window()

我正在寻找一种解决方案,可以动态调整页眉框的大小,因为我正在制作的应用程序根据文件的内容创建页眉,因此它们将不断变化,并且我将无法依靠单一的大小。

python csv pyqt5 qtablewidget
1个回答
0
投票

经过一些研究,我发现用于调整QTreeWidget.header()大小的setResizeMode方法对于QTableWidget是不同的,应将其更改为setSectionResizeMode。这是我添加到populateTable函数末尾的确切代码:

for i, column in enumerate(range(CsvHandler.getCols(file))):
            self.csvView.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)
© www.soinside.com 2019 - 2024. All rights reserved.