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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM