简体   繁体   中英

Qt QTreeview currentChange is not emitted

I am trying to run some code when I select a new index in a QTreeView

In RoverPlanner.h

namespace Ui {
    class RoverPlanner;
}

class RoverPlanner : public QWidget
{
Q_OBJECT

public:
    explicit RoverPlanner(QWidget *parent = nullptr);
    void save_paths_from_tree(QTreeView* treeView);
    void load_paths_into_tree(QTreeView* treeView);
    std::vector<cuarl_path::Path> get_paths(const char* filename) const;
    void update_segment_editor();
    cuarl_path::Segment* addSegment();
    ~RoverPlanner();

private Q_SLOTS:
    void treeSelectionChanged(const QModelIndex& prevIndex, const QModelIndex& nextIndex);

private:
    Ui::RoverPlanner *ui;
};

In RoverPlanner.cpp


RoverPlanner::RoverPlanner(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::RoverPlanner)
{
    ui->setupUi(this);

    QPushButton* btnLoadPaths = this->findChild<QPushButton*>("btn_load_paths");
    QPushButton* btnSavePaths = this->findChild<QPushButton*>("btn_save_paths");
    QPushButton* btnExecutePath = this->findChild<QPushButton*>("btn_execute_path"  );
    QPushButton* btnAddSegment = this->findChild<QPushButton*>("btn_add_to_path");

    QTreeView* treeView = this->findChild<QTreeView*>("tree_paths");

    connect(btnLoadPaths, &QPushButton::clicked, this, [=]() { load_paths_into_tree(treeView); });

 connect(treeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &RoverPlanner::treeSelectionChanged); // This does not seem to properly bind the index chan

}

void RoverPlanner::treeSelectionChanged(const QModelIndex &prevIndex, const QModelIndex &nextIndex) {
    std::cout << "Test" << std::endl;
}

//other functions

When I click on the items, it does not output anything in the console在此处输入图像描述

I'm confused because this seems to be the way to correctly connect the treeview selected index changed. What did I do wrong?

selectionModel gets replaced each time a new model is set for QTreeView .

void QAbstractItemView::setModel(QAbstractItemModel *model) :

This function will create and set a new selection model, replacing any model that was previously set withsetSelectionModel() .

That means you need to reconnect the &QItemSelectionModel::currentChanged signal each time you set a new model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM