目录
源码下载地址
https://download.youkuaiyun.com/download/Redboy_Crazy/12285656
1.简介
本文主要介绍了在QTableWidget表格中如何新增1行或者删除1行,并有动态效果图展示方便用于查看实际效果功能。
回目录
2.效果图
3.重点讲解
1) 新增行使用的是表格的插入函数,插入1行后,原有行及后面行的行号依次自动+1(插入行的位置这里需要理解下); ui->tableWidget->insertRow(newRow);
2)默认启动时,空表格是未有行被选中,因此新增行按照在行尾新增的方式处理。
3)表格未有行被选中时,以下表格当前行函数返回值为-1;
int curRow = ui->tableWidget->currentRow();
4.源码
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_btnAdd_clicked();
void on_btnDel_clicked();
private:
void initForm(); // 初始化控件
private:
Ui::Widget *ui;
int m_contNum; // 新增时的单元格内容,方便识别
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_contNum = 0;
initForm();
}
Widget::~Widget()
{
delete ui;
}
void Widget::initForm()
{
QStringList headerLabs({"列1","列2","列3","列4"});
ui->tableWidget->setHorizontalHeaderLabels(headerLabs);
ui->tableWidget->setColumnCount(headerLabs.size());
}
void Widget::on_btnAdd_clicked()
{
int rowCount = ui->tableWidget->rowCount();
m_contNum++;
QString strCont = QString::number(m_contNum);
int curRow = ui->tableWidget->currentRow();
qDebug() << curRow;
int newRow = curRow + 1;
QString strMsg;
if( -1 == curRow ){
newRow = rowCount;
strMsg = QString("在行尾插入1行,内容全部为%1").arg(strCont);
}else{
strMsg = QString("在第%1行后插入1行,内容全部为%2").arg(newRow).arg(strCont);
}
ui->pTextEdit->appendPlainText(strMsg);
ui->tableWidget->insertRow(newRow);
int colCount = ui->tableWidget->columnCount();
for(int col=0; col<colCount; col++){
QTableWidgetItem *it = new QTableWidgetItem(strCont);
ui->tableWidget->setItem(newRow, col, it);
}
}
void Widget::on_btnDel_clicked()
{
int curRow = ui->tableWidget->currentRow();
qDebug() << curRow;
QString strMsg;
if( -1 == curRow ){
strMsg = QString("未选中行,无法删除");
}else{
strMsg = QString("删除第%1行").arg(curRow+1);
}
ui->pTextEdit->appendPlainText(strMsg);
ui->tableWidget->removeRow(curRow);
}
加油,向未来!GO~
Come on!