PySide2 QTableWidget常用方法

QTableWidget 设置列宽模式

# 设置列宽模式为自动调整(自动拉伸列宽填充窗口,无法手动调整)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 设置列宽模式为手动调整
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
# 设置列宽模式为固定值模式(无法手动调整)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
# 设置最后一列拉伸填满窗口
self.tableWidget.horizontalHeader().setStretchLastSection(True)

# 搭配使用1 (整体自动调整,第一列可以手动调整)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)
# 搭配使用2 (整体自动调整,第一列自适应内容调整列宽)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
# 搭配使用3 (整体自动调整,第一列设置固定列宽)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.Fixed)
self.tableWidget.setColumnWidth(0, 80)

QTableWidget 设置表格编辑状态

# 表格可编辑
self.tableWidget.setEditTriggers(QAbstractItemView.DoubleClicked) # 双击触发
self.tableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) # 设置可多选
self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) # 设置行选中
# 清除选中状态
self.tableWidget.setCurrentItem(None)
# 表格不可编辑
self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableWidget.setSelectionMode(QAbstractItemView.NoSelection)
self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

QTableWidget 获取选中行索引

 # 方法1
 row_idx = self.tableWidget.selectedItems()[0].row() # 获取行索引
 self.tableWidget.removeRow(row_idx) # 删除行
 # 方法2
 row_idx = self.tableWidget.selectionModel().selectedRows()[0].row() # 获取行索引
 self.tableWidget.removeRow(row_idx) # 删除行

QTableWidget设置某列不可选中、不可编辑

row_count = self.tableWidget.rowCount()
for i in range(row_count):
    item = QTableWidgetItem(str(i + 1)) # 设置单元格文本
    item.setTextAlignment(Qt.AlignCenter) # 文本居中
    item.setFlags(QtCore.Qt.ItemIsEnabled) # 不可选中、不可编辑
    # item.setFlags(item.flags() & (~QtCore.Qt.ItemIsEditable)) # 可选中、不可编辑
    self.tableWidget.setItem(i, 0, item) # 填充第一列

QTableWidget导出内容为CSV文件

import pandas as pd

def save_to_csv(table: QTableWidget, file: str):
	"""保存测点信息至CSV文件"""
	 col_headers = []
	 for j in range(table.columnCount()):
	     col_headers.append(table.horizontalHeaderItem(j).text())
	 df = pd.DataFrame(columns=col_headers)
	
	 for row in range(table.rowCount()):
	     for col in range(table.columnCount()):
	         item = table.item(row, col)
	         df.at[row, col_headers[col]] = item.text() if item is not None else ""
	 df.to_csv(file, index=False)

QTableWidget填充CSV文件内容

import pandas as pd

    def read_device_message_from_csv(table: QTableWidget, file: str):
        """从CSV文件读取测点信息"""
        table.clear()  # 清空原有表格内容
        # 读取文件
        df = pd.read_csv(file)  # 打开读取excel表格
        row = df.shape[0]  # 获取表格行数
        col = df.shape[1]  # 获取表格列数
        table_header = list(df.columns)  # 获取表头
        table.setColumnCount(col)  # 设置表格列数
        table.setRowCount(row)  # 设置表格行数
        table.setHorizontalHeaderLabels(table_header)  # 给tableWidget设置行列表头

        for i in range(row):  # 行循环
            for j in range(col):  # 列循环
                table_item = str(df.iloc[i, j])  # 该数据转换成字符串
                new_item = QTableWidgetItem(table_item)  # 该字符串类型的数据新建为tableWidget元素
                new_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)  # 显示为水平居中、垂直居中
                table.setItem(i, j, new_item)  # 在表格第i行第j列显示newItem元素
            pass

QTableWidget单元格添加QPushButton等控件

def get_button_widget(slot, text=""):
    """生成包含QLineEdit,QPushButton的QWidget组件"""
    widget = QtWidgets.QWidget()
    line_edit = QtWidgets.QLineEdit(text)
    # 设置样式
    line_edit.setStyleSheet("QLineEdit{\n"
                            "margin: 2px 2px 2px 2px;\n"
                            "background-color:rgba(167, 243, 228, 100);\n"
                            "border-radius: 5px;\n"
                            "}\n")

    btn = QtWidgets.QPushButton('获取')
    # 设置样式
    btn.setStyleSheet(".QPushButton {\n"
                      "margin: 2px 2px 2px 2px;\n"
                      "font-size:18px;\n"
                      "min-width:90px;\n"
                      "padding:5px;\n"
                      "border-radius: 5px;\n"
                      "background-color: rgba(156, 178, 206, 150);\n"
                      "}\n"
                      "\n"
                      ".QPushButton:hover{\n"
                      "background-color: rgba(109, 125, 144, 200);\n"
                      "}\n"
                      "\n"
                      ".QPushButton:pressed{\n"
                      "background-color: rgb(109, 125, 144);\n"
                      "}\n")

    hbox_layout = QtWidgets.QHBoxLayout()
    hbox_layout.addWidget(line_edit)
    hbox_layout.addWidget(btn)
    hbox_layout.setContentsMargins(4, 0, 4, 0)
    widget.setLayout(hbox_layout)
    btn.clicked.connect(slot)
    return widget

表格某列添加QPushButton等控件
def add_cellwidget(table, col)
	for i in range(table.rowCount()):
	    table.setCellWidget(i, col, get_button_widget(slot))
	    item = table.item(i, col)
	    if item is None:
	        item = QTableWidgetItem('')
	        table.setItem(i, col, item)
	    # 设置填充控件单元格不可选中、不可编辑
	    item.setFlags(QtCore.Qt.ItemIsEnabled)

QTableWidget 样式

/*表格的一种美化方式*/
QHeaderView{
    /*font-size:18px;*/
    background:transparent;
}
QTableCornerButton::section{
	background:rgb(126, 145, 176);
}

QHeaderView::section{
    color:#FFFFFF;
    background:rgb(126, 145, 176);
    border:none;
	border-left: 1px solid #333333;
    text-align:center;
    padding-left:2px;
	padding-right:2px;
}

QTableWidget{
    background:#FFFFFF;
    border:none;
	outline:none;
    /*font-size:18px;*/
    color:#666666;
}

QTableWidget::item{
	border-left:1px solid #EEF1F7;
    border-bottom:1px solid #EEF1F7;
}

QTableWidget::item::selected{
    color:rgb(0, 0, 0);
    background:#EFF4FF;
}
/* QScrollBar Vertical Style */
QScrollBar::vertical{
background:transparent;
width:12px;
border:none;
}

QScrollBar::add-line:vertical{
background:none;
border:none;
}

QScrollBar::sub-line:vertical{
background:none;
border:none;
}

QScrollBar::add-page:vertical{
background:transparent;
border:none;
}

QScrollBar::sub-page:vertical{
background:transparent;
border:none;
}

QScrollBar::handle:vertical{
background: rgba(111, 134, 147, 100);
border-radius:4px;

}

QScrollBar::handle:vertical:hover{
background: rgba(111, 134, 147, 180);
}

QScrollBar::handle:vertical:pressed{
background: rgba(111, 134, 147, 255);
}

/* QScrollBar Horizontal Style */
QScrollBar::horizontal{
background:transparent;
height:12px;
border:none;
}

QScrollBar::add-line:horizontal{
background:none;
border:none;
}

QScrollBar::sub-line:horizontal{
background:none;
border:none;
}

QScrollBar::add-page:horizontal{
background:transparent;
border:none;
}

QScrollBar::sub-page:horizontal{
background:transparent;
border:none;
}

QScrollBar::handle:horizontal{
background: rgba(111, 134, 147, 100);
border-radius:4px;

}

QScrollBar::handle:horizontal:hover{
background: rgba(111, 134, 147, 180);
}
QScrollBar::handle:horizontal:pressed{
background: rgba(111, 134, 147, 255);
}



在这里插入图片描述

未完待续······

PySide2 QTableWidget is a GUI component in the PySide2 library that provides a table view widget for displaying and editing tabular data. It is similar to a spreadsheet or a database table, where the data is arranged in rows and columns. To use QTableWidget, you need to import the module and create an instance of the QTableWidget class. You can set the number of rows and columns, and populate the cells with data using the setItem() method. Here's an example code snippet that creates a QTableWidget with two columns and three rows: ```python from PySide2.QtWidgets import QApplication, QTableWidget, QTableWidgetItem app = QApplication([]) table = QTableWidget(3, 2) # 3 rows, 2 columns # Set the headers for the columns table.setHorizontalHeaderLabels(['Name', 'Age']) # Populate the cells with data table.setItem(0, 0, QTableWidgetItem('Alice')) table.setItem(0, 1, QTableWidgetItem('25')) table.setItem(1, 0, QTableWidgetItem('Bob')) table.setItem(1, 1, QTableWidgetItem('30')) table.setItem(2, 0, QTableWidgetItem('Charlie')) table.setItem(2, 1, QTableWidgetItem('35')) table.show() app.exec_() ``` This code creates a table with two columns: "Name" and "Age", and populates the cells with data for three people. The `show()` method displays the table, and `exec_()` starts the application event loop. You can also customize the appearance and behavior of the QTableWidget by setting properties and connecting signals and slots. For example, you can enable editing of cells, set the selection mode, and handle cell clicks and edits.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值