mouseEvent
上车的问题QTableWidget
,这段代码是创建一个窗口tabelwidget
,mouseclickevent
当我单击鼠标右键时,我有两个名为“添加”和“删除”的动作事件选项,我想在单击时添加 3 列的新行“添加”事件功能,并在我单击“删除”事件功能时删除最后一行,
(对不起我的英语),任何帮助表示赞赏。
#include "notepad.h"
#include <QMessageBox>
#include <QTableView>
#include <QMouseEvent>
Notepad::Notepad()
{
test() ;
add_action = new QAction(tr("Add cell"), this);
add_action->setIcon(QIcon("add.jpg"));
Delete_action = new QAction(tr("Delete cell"), this);
Delete_action->setIcon(QIcon("delete.jpg"));
connect(Delete_action, SIGNAL(triggered()), this, SLOT(Delete()));
connect(add_action, SIGNAL(triggered()), this, SLOT(add()));
centralWidget()->setAttribute(Qt::WA_TransparentForMouseEvents);
centralWidget()->setAttribute(Qt::WA_MouseTracking,true);
setMouseTracking(true);
}
void Notepad::test()
{
QTableWidget* table = new QTableWidget();
QTableWidgetItem* tableItem = new QTableWidgetItem();
table->setRowCount(1);
table->setColumnCount(3);
table->setItem(0,0,new QTableWidgetItem());
table->setItem(0,1,new QTableWidgetItem());
table->setItem(0,2,new QTableWidgetItem());
table->setMouseTracking(true);
table->viewport()->setMouseTracking(true);
table->installEventFilter(this);
table->viewport()->installEventFilter(this);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);
tableItem->setFlags(tableItem->flags() ^ Qt::ItemIsEditable);
table->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
setCentralWidget(table);
}
void Notepad::mouseReleaseEvent (QMouseEvent * event )
{
QMessageBox* msgBox;
if(event->button() == Qt::RightButton)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);
QMenu *menu = new QMenu(this);
menu->addAction(add_action);
menu->addAction(Delete_action);
menu->exec(mouseEvent->globalPos());
}
}
void Notepad::add()
{
QTableWidget* table = new QTableWidget();
test();
table->setColumnCount(3);*/
int newRow = table->rowCount();
int newcol = table->columnCount();
qDebug() << newRow;
for (int row ; row < newRow+1 ; ++row)
{
QWidget *parent;
QStyleOptionViewItem option;
for (int column = 0; column < 3; ++column)
{
table->insertRow( table->rowCount());
table->insertColumn( newcol );
}
}
setCentralWidget(table);
centralWidget()->setAttribute(Qt::WA_TransparentForMouseEvents);
setMouseTracking(true);
}
void Notepad::Delete()
{
QTableWidget* table = new QTableWidget();
add();
int row=table->rowCount();
if (int i= row){
table->removeRow(i);
}
setCentralWidget(table);
centralWidget()->setAttribute(Qt::WA_TransparentForMouseEvents);
setMouseTracking(true);
}