首页 > 解决方案 > Qt QTreeview currentChange 没有发出

问题描述

当我在 QTreeView 中选择一个新索引时,我正在尝试运行一些代码

在 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;
};

在 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

当我单击项目时,它不会在控制台中输出任何内容 在此处输入图像描述

我很困惑,因为这似乎是正确连接 treeview 选择索引更改的方法。我做错了什么?

标签: c++qtqtreeview

解决方案


每次为 设置新模型时,selectionModelQTreeView都会被替换。

无效 QAbstractItemView::setModel(QAbstractItemModel *model)

此函数将创建并设置一个新的选择模型,替换之前使用setSelectionModel()设置的任何模型。

&QItemSelectionModel::currentChanged这意味着每次设置新模型时都需要重新连接信号。


推荐阅读