QTableView – 没有获得选择更改信号

我对QT很新,并且无法理解如何处理QTableView选择改变信号.我已经设置了一个带有openGL小部件和QTableView的窗口.我有一个正确填充tableview的数据模型类,所以我在该类中添加了一个公共插槽:

class APartsTableModel : public QAbstractTableModel
{
public:
    AVehicleModel *vehicle;
    explicit APartsTableModel(QObject *parent = 0);

    //MVC functions
    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &paret) const;
    QVariant data(const QModelIndex &index, int role) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

public slots:
    void selectionChangedSlot(const QItemSelection &newSelection,
                              const QItemSelection &oldSelection);

};

当我准备用表视图显示窗口时,我像这样分配/初始化它:

//create the display view
AStarModelView *displayWindow = new AStarModelView(this,
                                                   starModel->vehicle);

//create the datamodel for the table view
APartsTableModel *dataModel = new APartsTableModel(displayWindow);
dataModel->vehicle = starModel->vehicle;

//create selection model for table view
QItemSelectionModel *selModel = new QItemSelectionModel(dataModel);
displayWindow->materialsTable->setSelectionModel(selModel);

//setup model and signal
displayWindow->materialsTable->setModel(dataModel);

connect(selModel,
        SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
        dataModel,
        SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &)));

//show the view
displayWindow->show();

当我在插槽函数的实现中设置断点时,我从未点过它.我也尝试过不分配新的QItemSelectionModel,但这也不起作用.我真的不确定我在这里做错了什么.

最佳答案 在视图上调用setModel()时,本地分配的QItemSelectionModel将被视图创建的QItemSelectionModel替换.无论如何,您不必创建自己的选择模型.只需将连接更改为

connect(displayWindow->materialsTable->selectionModel(),
        SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
        dataModel,
        SLOT(selectionChangedSlot(const QItemSelection&, const QItemSelection&)));
点赞