QT之QTableWidget基本使用

#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //tableWidget表格控件使用

    //设置列数
    ui->tableWidget->setColumnCount(3);

    //设置水平表头
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"姓名"<<"性别"<<"年龄");


    //设置行数
    ui->tableWidget->setRowCount(5);

    QList<QString> nameList;
    nameList << "亚瑟"<< "安琪拉"<<"妲己"<<"东皇太一"<< "孙膑";
    QStringList sexList;
    sexList << "男"<< "女"<< "女"<< "男"<< "中立";


    for(int i  = 0 ; i < 5;i++)
    {
        int col = 0;
        ui->tableWidget->setItem(i,col++, new QTableWidgetItem(nameList[i]));

        ui->tableWidget->setItem(i,col++, new QTableWidgetItem(sexList.at(i)));

        //int 转 QString   QString::number(int)
        ui->tableWidget->setItem(i,col++, new QTableWidgetItem( QString::number(i+18)  ));
    }

	//点击按钮添加 后羿
	connect(ui->addBtn,&QPushButton::clicked,[=](){
		bool isEmpty = ui->tableWidget->findItems("后羿",QT::MatchExactly).empty();
		if(isEmpty){
			ui->tableWidget->insertRow(0);
			ui->tableWidget->setItem(0,0,new QTableWidgetItem("后羿"));
			ui->tableWidget->setItem(0,1,new QTableWidgetItem("男"));
			ui->tableWidget->setItem(0,2,new QTableWidgetItem( QString::number(i+18)  ));
		}
		else{
			QMessageBox::warning(this,"Warning!已拥有后羿!");
		}
	});
	//点击按钮删除 后羿
	connect(ui->delBtn,&QPushButton::clicked,[=](){
		bool isEmpty = ui->tableWidget->findItems("后羿",QT::MatchExactly).empty();
		if(isEmpty){
			QMessageBox::warning(this,"Warning!没有后羿!");
		}
		else{
			//先找到赵云所在的行数
			int row_tmp = ui->tableWidget->findItems("后羿",QT::MatchExactly).first()->row();
			ui->tableWidget->removeRow(row_tmp);			
		}
	});



}

Widget::~Widget()
{
    delete ui;
}

上一篇:《阿里云科技评论》第一期


下一篇:localStorage的使用