Add and delete data in QTableWidget table

Case introduction

This case only briefly introduces some methods of using QTableWidget, such as inserting or deleting a row of data in the table and clearing the table data. When adding data, conditional judgments such as regular expressions are set. If the data entered by the user is illegal, the addition will fail and the user will be prompted for the error, making it easier for the user to modify.

As a benefit for this article, you can receive a Qt development learning package and technical videos for free , including (Qt practical projects, C++ language basics, C++ design patterns, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project practice, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article to receive the fee↓↓

UI interface design

As shown in the figure above, use the QWidget class to create and set up the UI interface, where the control descriptions are shown in the following table.

Program implementation

widge.h header file

Add three slot functions, on_addButton_clicked(): used to implement the function of adding data; on_delButton_clicked(): the user deletes a row of data selected by the user in the table; on_clearButton_clicked(): used to clear all data in the table.

private slots:
    void on_addButton_clicked();
    void on_delButton_clicked();
    void on_clearButton_clicked();

widget.cpp source file

Define the header in the constructor.

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QStringList header;
    header <<"姓名"<<"性别"<<"年龄"<<"电话号码";
    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setRowCount(0);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

on_addButton_clicked(): First get the content filled in by the user and determine whether the content is legal. For example, if the user does not fill in the name or age or fills in the wrong phone number, it is illegal. Regular expressions are used to determine whether the phone number is legal. If the information filled in by the user already exists in the form, a pop-up box will pop up to remind the user and the addition fails. If the input information is legal and the same name does not exist in the form, a new row will be created to insert the filled in information and a pop-up box will prompt that the insertion is successful. Finally clear the information in the input control.

void Widget::on_addButton_clicked()
{
    QString name=ui->nameEdit->text();
    int age=ui->ageBox->text().toInt();
    QString sex="男";
    if(ui->radioButton2->isChecked())
        sex="女";
    //正则表达式判断电话号码是否合法
    QRegularExpression exp;
    exp.setPattern("^1[3-9][0-9]{9}$");
    QString tele=ui->teleEdit->text();
    QRegularExpressionMatch match = exp.match(tele);
    if(name.length()==0)
        QMessageBox::information(this,"警告","请输入姓名!!!");
    else if(age==0)
        QMessageBox::information(this,"警告","请输入年龄!!!");
    else if(!match.hasMatch())
        QMessageBox::information(this,"警告","电话号码格式错误!!!");
    else
    {
        bool isEmpty = ui->tableWidget->findItems(name,Qt::MatchExactly).empty();
        if(isEmpty)
        {
            int index=ui->tableWidget->rowCount();
            ui->tableWidget->insertRow(index);    
            ui->tableWidget->setItem(index,0,new QTableWidgetItem(name));
            ui->tableWidget->setItem(index,1,new QTableWidgetItem(sex));
            ui->tableWidget->setItem(index,2,new QTableWidgetItem(QString::number(age)));
            ui->tableWidget->setItem(index,3,new QTableWidgetItem(tele));
            QMessageBox::information(this,"Done","用户添加成功!!!");
        }
        else
            QMessageBox::information(this,"Warning","该用户已存在,无法重复添加!!!");
    }
    //清空输入控件
    ui->nameEdit->clear();
    ui->radioButton1->setChecked(1);
    ui->ageBox->setValue(0);
    ui->teleEdit->clear();
}

on_delButton_clicked(): Get the number of rows selected by the user through the tableWidget->currentRow() function, and delete it through the tableWidget->removeRow() function.

on_clearButton_clicked(): Delete all data in the table row by row by looping.

void Widget::on_delButton_clicked()
{//删除在表中所选中的一行数据
    ui->tableWidget->removeRow(ui->tableWidget->currentRow());
}
void Widget::on_clearButton_clicked()
{//删除表中所有数据
    int n=ui->tableWidget->rowCount();
    for(int i=0;i<=n;i++)
        ui->tableWidget->removeRow(0);
}

function test

Add data function

After entering the correct and legal data and clicking Add, a box will pop up indicating that the addition was successful, as shown in the figure below:

Delete data and clear function

① Delete a row of data: First select the row where "李思" is located in the table, which is row 2, and click Delete.

② Clear all data: directly click the Clear All button. As shown below:

Exception handling testing

① Without entering your name, click Add directly. The pop-up box will prompt "Please enter your name!!!" and clear the filled content.

② When entering your name but not your age, click Add. A pop-up box will prompt "Please enter your age!!!" and clear the filled content.

③After entering your name and age, enter an incorrect phone number and click Add. A pop-up box will prompt "The phone number format is incorrect!!!" and clear the filled content. As shown below:

④Insert users that already exist in the table, as shown in the figure below:

As a benefit for this article, you can receive a Qt development learning package and technical videos for free , including (Qt practical projects, C++ language basics, C++ design patterns, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project practice, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/132900714