QT--QTableWidget单击单元格后获取行号

在qtablewidget中获取当前选定行号的方法:
方法一:通过QList QTableWidget::SelectedRanges()获取当前选定的范围,然后根据所选范围的起止进行行号判断。
方法二:通过cellClicked(int,int)信号先获取当前鼠标点击单元格坐标,然后判断所在行号,该方法在设定表格每次选择一整行时,效果更好。

以下为部分核心代码:

ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);		//设置整行选择
ui.tableWidget->wetSelectionMode(QAbstractItemView::SingleSelection);		//设置只选择一行

方法一:QTableWidget::SelectedRanges()

QList<QTableWidgetSelectionRange> ranges = ui.tableWidget->selectedRanges();
if(ranges.count() == 0)
{
    qDebug() << QStringLiteral("请选择一行");
}
else
{
    for(int i  = 0; i < ranges.count(); i++)
    {
        	int topRow=ranges.at(i).topRow();

                    int bottomRow=ranges.at(i).bottomRow();

        for(int j = topRow; j <= bottomRow; j++)

       {
          qDebug()<<QstringLiteral("当前选择行号为:")<<j;
        }
    }
}

ranges四个参数

1.topRow:所选区域的开始行号;
2.bottomRow:所选区域的截止行号;
3.left:所选区域的开始列号;
4.right:所选区域的结束列号。

方法二:cellClicked(int,int)
头文件定义:

signals:
		void  sendCurrentSelectedRow(int nRow);			//发送当前行号
private slots:
		void  onCilckTable(int nRow, int nCol);				//获取当前点击的单元格行、列号
		void onCurrentSelectedRow(int nRow);				//响应sendCurrentSelectedRow信号
private:
		int m_nCurrentSelectedRow;				//当前选择行号

实现:

connect(ui.tableWidget, SIGNAL(cellClicked(int, int)), this, SLOT(onClickTable(int, int)));
connect(this, SIGNAL(sendCurrentSelectedRow(int)), this, SLOT(onCurrentSelectedRow(int)));

onCilckTable(int nRow, int nCol)槽函数

ui.tableWidget->setCurrentCell(nRow, QItemSelectionModel::Select);		//设置选择当前行
emit sendCurrentSelectedRow(nRow);

nCurrentSelectedRow(int nRow)槽函数

m_nCurrentSelectedRow = nRow;				//当前选择的行号

小结
上述两种方法均可获取当前选择行号,读者可根据需要自行选择。

https://blog.csdn.net/weixin_39935783/article/details/111668635

posted @ 2021-01-28 17:01  手磨咖啡  阅读(5253)  评论(0编辑  收藏  举报