我创建了一个QTableWidget。一些单元格填充了一个单元格小部件(修改后的QLabel,发送一个单击的信号)。 现在,我想点击这个标签做出反应。我添加了一些调试功能。
单击空单元格将正确的行和列写入控制台。 单击标签会重新识别为单击,但行和列错误(使用前一个单元格数据)。
问题:如何在点击标签时获得正确的行和列。
问候和感谢,迈克尔
MtTimeTable::MtTimeTable( QWidget* parent )
: QTableWidget { parent }, mIdArray { MtIdArray() },
mDate { QDate::currentDate() }
{
this->fillLesssonWidgets();
connect( this, &MtTimeTable::cellClicked,
this, &MtTimeTable::slotCellActivated );
}
void MtTimeTable::fillLessonWidgets()
{
MtLessonVec lessonVec { true }; // Data to show, loaded from file
auto cit { lessonVec.begin() };
while( cit != lessonVec.end() ) {
// Class MtLessonWidget derived from QLabel
MtLessonWidget* lessonWidget { new MtLessonWidget };
lessonWidget->setLesson( *cit );
// Using member functions of MtLessonwidget, working correct
this->setCellWidget( lessonWidget->startingRow(),
lessonWidget->startingCol(),
lessonWidget );
}
connect( lessonWidget, &MtLessonWidget::sigClicked,
this, &MtTimeTable::slotLessonWidgetClicked );
++cit;
}
}
我试图将代码减少到最低限度。
void MtTimeTable::slotLessonWidgetClicked()
{
std::cerr << "Table Cell: [" << this->currentRow() << ","
<< this->currentColumn() << "]" << std::endl;
}
答案 0 :(得分:1)
根据docs:
int QTableWidget :: currentColumn()const
返回当前项的列。
int QTableWidget :: currentRow()const
返回当前项的行。
也就是说,它是项目的位置,它引用了一个QTableWidgetItem,但是如果我们使用setCellWidget没有创建一个项目,那么这些位置是不合适的,我们必须寻找另一种方法来获取行和与小部件关联的列。
一种方法是使用indexAt()
方法返回与该单元格关联的QModelIndex
,并确定其相对于viewport()
QTableWidget
的位置,这就是一个应该使用:
void MtTimeTable::slotLessonWidgetClicked(){
auto lbl = qobject_cast<MtLessonWidget *>(sender());
if(lbl){
auto ix = indexAt(lbl->pos());
qDebug()<<"Table Cell: [" <<ix.row()<< "," <<ix.column()<< "]";
}
}
完整示例:
#include <QApplication>
#include <QLabel>
#include <QTableWidget>
#include <QDebug>
class CustomLabel: public QLabel{
Q_OBJECT
protected:
void mousePressEvent(QMouseEvent *){
emit clicked();
}
signals:
void clicked();
};
class TableWidget: public QTableWidget{
Q_OBJECT
public:
TableWidget(QWidget* parent=Q_NULLPTR):QTableWidget(parent){
setRowCount(10);
setColumnCount(10);
for(int i=0; i<rowCount(); i++){
for(int j=0; j<columnCount(); j++){
auto lbl = new CustomLabel;
setCellWidget(i, j, lbl);
connect(lbl, &CustomLabel::clicked, this, &TableWidget::onClicked);
}
}
}
private slots:
void onClicked(){
auto lbl = qobject_cast<CustomLabel *>(sender());
if(lbl){
auto ix = indexAt(lbl->pos());
qDebug()<<"Table Cell: [" <<ix.row()<< "," <<ix.column()<< "]";
}
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TableWidget w;
w.show();
return a.exec();
}
在以下链接中,我展示了完整的example。