2016-03-03 751 views
0

我在每一行都有一个删除按钮。我正在尝试使用QTableview的clicked()SIGNAL来获取当前索引,然后做相应的操作,但在这种情况下不调用此插槽。由于某种原因它不起作用,我在连接clicked()SIGNAL时犯了一些错误吗?QTableView:如何正确使用clicked()信号来获取所选项目的索引?

void MyClass::myFunction() 
    { 
      ComboBoxItemDelegate* myDelegate; 
      myDelegate = new ComboBoxItemDelegate(); 
      model = new STableModel(1, 8, this); 
      filterSelector->tableView->setModel(model); 
      filterSelector->tableView->setItemDelegate(myDelegate); 
      connect(filterSelector->tableView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(slotHandleDeleteButton(const QModelIndex&))); 
      exec(); 
    } 

    void MyClass::slotHandleDeleteButton(const QModelIndex& index) 
    { 
     if(index.column() == 8) 
      model->removeRow(index.row()); 
    } 
+0

MyClass是否来自'SFilterEditor'? – Tomas

+0

我编辑了代码,请审查。 – wazza

+0

我想它适用于除按钮之外的所有列。对? – Tomas

回答

0

一种解决方案可以是这样的:

class Button : public QPushButton 
{ 
    Q_OBJECT 
public: 
    Button(int row, QWidget *parent = 0) : QPushButton(parent), m_row(row) 
    { 
     connect(this, SIGNAL(clicked()), this, SLOT(onClicked())); 
    } 

signals: 
    void clicked(int row); 

private slots: 
    void onClicked() 
    { 
     emit clicked(m_row); 
    } 
private: 
    int m_row; 
}; 

Button类包含行号作为参数的自定义信号clicked(int)。要在你的表格视图中使用它,你需要这样做:

Button *btn = new Button(rowNumber, this); 
connect(btn, SIGNAL(clicked(int)), this, SLOT(onButtonClicked(int))); 
+0

对不起,迟到的回复,我尝试过,但这种方法存在问题。 @vahancho由于这些删除按钮删除整行,所以当第5行中的第3行被删除时,下行(第4和第5)中删除按钮的索引不会更新。我的意思是第4行现在是第3行,但是为其删除按钮存储的索引将是第4行,这将导致删除按钮索引和行索引(rowPosition)之间的不一致。 – wazza

相关问题