QTableWidget的使用案例
创建QTableWidget
m_table_widget = new QTableWidget(this);
m_table_widget->setObjectName("TableWidget");
m_table_widget->setShowGrid(false);
m_table_widget->setSortingEnabled(true);
m_table_widget->setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);
m_table_widget->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
m_table_widget->setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
m_table_widget->setColumnCount(5);
m_table_widget->setHorizontalHeaderLabels({TU(""), TU("文件名称"), TU("日期"), TU("类型"), TU("大小")});
m_table_widget->verticalHeader()->setVisible(false);
m_table_widget->horizontalHeader()->resizeSection(0, 50);
m_table_widget->horizontalHeader()->resizeSection(2, 140);
m_table_widget->horizontalHeader()->resizeSection(3, 100);
m_table_widget->horizontalHeader()->resizeSection(4, 100);
m_table_widget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Fixed);
m_table_widget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeMode::Stretch);
m_table_widget->verticalScrollBar()->setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu);
m_table_widget->horizontalScrollBar()->setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu);
connect(m_table_widget, &QTableWidget::itemSelectionChanged, this, &Widget::itemSelectionChanged);
connect(m_table_widget, &QTableWidget::itemClicked, this, &Widget::itemClicked);
添加数据
for(int row = 0; row < 10; ++row)
{
m_table_widget->insertRow(m_table_widget->rowCount());
auto item = new QTableWidgetItem();
item->setIcon(QIcon("D:\\wsl.ico"));
item->setCheckState(Qt::CheckState::Unchecked);
m_table_widget->setItem(row, 0, item);
m_table_widget->setItem(row, 1, new QTableWidgetItem(QString("filename_xxxxx_%1").arg(row)));
m_table_widget->setItem(row, 2, new QTableWidgetItem("2024/01/01 10:00:00"));
m_table_widget->setItem(row, 3, new QTableWidgetItem("xxxxx.txt"));
m_table_widget->setItem(row, 4, new QTableWidgetItem("124000KB"));
}
清空数据
while(m_table_widget->rowCount() > 0)
{
m_table_widget->removeRow(m_table_widget->rowCount() - 1);
}
处理选择
在选择了行时,设置复选框的选中状态。
void Widget::itemSelectionChanged()
{
for(int row = 0; row < m_table_widget->rowCount(); ++row)
{
auto item = m_table_widget->item(row, 0);
if (item->isSelected())
{
item->setCheckState(Qt::CheckState::Checked);
}
else
{
item->setCheckState(Qt::CheckState::Unchecked);
}
}
}
处理单击
点击复选框后,设置行的选中状态。
if (0 == item->column())
{
if (Qt::CheckState::Checked == item->checkState())
{
m_table_widget->selectRow(item->row());
}
else if (Qt::CheckState::Unchecked == item->checkState())
{
for(int col = 0; col < m_table_widget->columnCount(); ++col)
{
m_table_widget->item(item->row(), col)->setSelected(false);
}
}
}