Qt QTableWidget某列为删除和添加按钮,点击删除当前行,点击添加添加一行。

实现:Qt QTableWidget某列为删除和添加按钮,点击删除当前行,点击添加添加一行。

一、运行效果图

QTableWidget.wmv

二、源码

1.头文件

#pragma once

#include 
#include "ui_QtableWidgetNB.h"

class QtableWidgetNB : public QWidget
{
	Q_OBJECT

public:
	QtableWidgetNB(QWidget *parent = Q_NULLPTR);
	~QtableWidgetNB();
	void addRow(QString & name);
	void removeRow(int nRow);

public slots:
	void sltBtnAddClicked();
	void sltBtnDeleteClicked();

private:
	Ui::QtableWidgetNB ui;
};

2、源文件

#include "QtableWidgetNB.h"
#include 
#include 
#include 

Q_DECLARE_METATYPE(QTableWidgetItem*)

QtableWidgetNB::QtableWidgetNB(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	QStringList headList;
	headList << QStringLiteral("姓名") << QStringLiteral("操作");
	ui.tableWidget->setColumnCount(2);
	ui.tableWidget->setHorizontalHeaderLabels(headList);

	addRow(QStringLiteral("妲己"));
	addRow(QStringLiteral("貂蝉"));
	addRow(QStringLiteral("孙尚香"));
	addRow(QStringLiteral("大乔"));

}

QtableWidgetNB::~QtableWidgetNB()
{
}

void QtableWidgetNB::sltBtnAddClicked()
{
	QString str="";
	addRow(str);
}

void QtableWidgetNB::sltBtnDeleteClicked()
{
	QPushButton * pBtn = dynamic_cast<QPushButton*>(sender());
	if (NULL == pBtn)
	{
		return;
	}
	QTableWidgetItem* item = pBtn->property("item").value<QTableWidgetItem*>();
	if (NULL == item)
	{
		return;
	}
	int nRow = ui.tableWidget->row(item);
	removeRow(nRow);
}

void QtableWidgetNB::addRow(QString & name)
{
	// 在tableWidget里插入项
	int nRow = ui.tableWidget->rowCount();
	ui.tableWidget->setRowCount(nRow+1);
	QTableWidgetItem * pItem1 = new QTableWidgetItem(name);
	ui.tableWidget->setItem(nRow, 0, pItem1);

	// 操作按钮
	QPushButton* pBtnAdd = new QPushButton(QStringLiteral("添加"));
	connect(pBtnAdd, &QPushButton::clicked, this, &QtableWidgetNB::sltBtnAddClicked);

	QPushButton* pBtnDelete = new QPushButton(QStringLiteral("删除"));
	pBtnDelete->setProperty("item", QVariant::fromValue(pItem1));
	connect(pBtnDelete, &QPushButton::clicked, this, &QtableWidgetNB::sltBtnDeleteClicked);

	QWidget * pOperationWidget = new QWidget(ui.tableWidget);
	QHBoxLayout * pHblayOperation = new QHBoxLayout(pOperationWidget);
	pHblayOperation->setContentsMargins(0, 0, 0, 0);
	pHblayOperation->addWidget(pBtnAdd);
	pHblayOperation->addWidget(pBtnDelete);
	ui.tableWidget->setCellWidget(nRow , 1, pOperationWidget);
}

void QtableWidgetNB::removeRow(int nRow)
{
	if (nRow >= 0)
	{
		ui.tableWidget->removeRow(nRow);
	}
}

你可能感兴趣的:(Qt,qt)