QTableWidget获取游标所在行号和列号的正确姿势

最近笔者在项目开发过程中需要获取QTableWidget的光标位置,琢磨了一段时间,拿出来和大家分享一下。

1.先说正确的姿势:

connect(this, &QTableWidget::itemSelectionChanged, [=]()
{
    qDebug() << "row = " << currentRow();
    qDebug() << "column = " << currentColumn();
});

PS:如果setCellWidget(int row, int column, QWidget *widget)之后光标上下左右移动不正常(如setCellWidget(2, 3, new QPushButton)),可以试着将QPushButton的聚焦策略改为Qt::NoFocus;

2.错误的姿势:

#if true
void TableWidget::keyPressEvent(QKeyEvent *event) 
{
    qDebug() << "row = " << currentRow();
    qDebug() << "column = " << currentColumn();
    QTableWidget::keyPressEvent(event);
}

void TableWidget::mouseReleaseEvent(QMouseEvent *event) 
{
    qDebug() << "row = " << currentRow();
    qDebug() << "column = " << currentColumn();
    QTableWidget::mouseReleaseEvent(event);
}
#endif

#if true
void TableWidget::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "row = " << moveCursor(QAbstractItemView::MoveRight, Qt::KeyboardModifierMask).row();
    qDebug() << "column = " << moveCursor(QAbstractItemView::MoveRight, Qt::KeyboardModifierMask).column();
    QTableWidget::keyPressEvent(event);
}

void TableWidget::mouseReleaseEvent(QMouseEvent *event)
{
    qDebug() << "row = " << moveCursor(QAbstractItemView::MoveRight, Qt::KeyboardModifierMask).row();
    qDebug() << "column = " << moveCursor(QAbstractItemView::MoveRight, Qt::KeyboardModifierMask).column();
    QTableWidget::mouseReleaseEvent(event);
}
#endif

PS:单元格坐标到边界位置会出现异常,引以为戒;

你可能感兴趣的:(qt)