實例QT程序 —— QTableWidget 表格新增/刪除行功能

目錄

1.簡介
2.效果圖
3.重點講解
4.源碼



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!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章