C++ QListView selectionModel未发送selectionChanged信号

C++ QListView selectionModel未发送selectionChanged信号,c++,qt,listview,signals,C++,Qt,Listview,Signals,我有一个带有两个qlistView的界面,其中左侧决定右侧显示的内容: 要更新右侧的列表,我有以下功能: void CodePlug::handleSelectionChanged() { QModelIndex portIndex = ui->listPorts->currentIndex(); QString portItemText = portIndex.data(Qt::DisplayRole).toString(); ui->listPlu

我有一个带有两个
qlistView
的界面,其中左侧决定右侧显示的内容:

要更新右侧的列表,我有以下功能:

void CodePlug::handleSelectionChanged()
{
    QModelIndex portIndex = ui->listPorts->currentIndex();
    QString portItemText = portIndex.data(Qt::DisplayRole).toString();
    ui->listPlugs->setModel(ListModelFromMap(plugs[portItemText]));
    currentPort = portItemText;
    qDebug(currentPort.toStdString().data());
}
它在这里连接到selectionChanged信号:

CodePlug::CodePlug(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CodePlug)
{
    ui->setupUi(this);
    ui->listPorts->setModel(ListModelFromMap(ports));
    QModelIndex portIndex = ui->listPlugs->currentIndex();
    QString portItemText = portIndex.data(Qt::DisplayRole).toString();
    ui->listPlugs->setModel(ListModelFromMap(plugs[portItemText]));

    connect(ui->listPorts->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSelectionChanged()));
}

但是,通过键盘或鼠标更改所选项目不会触发
handleSelectionChanged()
。它不会产生任何错误,只是什么都不做。有人能告诉我为什么吗?

我觉得连接不错。确实没有看到任何运行时错误吗?下面是一些检查它们是否有用的东西

1) 检查是否已将
Q_对象
宏添加到
CodePlug
类标题中。如果没有,请添加它并再次运行qmake

class CodePlug : public QMainWindow
{
    Q_OBJECT
2) 检查是否已将
handleSelectionChanged
定义为插槽

private slots:
    void handleSelectionChanged();
3) 检查
connect
是否实际成功,方法是检查它返回的内容

bool ret = connect(ui->listPorts->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSelectionChanged()));
4) 测试信号是否通过连接到例如handleCurrentChanged插槽来触发

可能的错误:

  • 函数
    handleSelectionChanged()
    是否定义为专用/公用插槽
  • 是默认的
    qabstractemview::NoSelection
    尝试强制进行单个/多个选择:

    ui->listPorts->setSelectionMode(QItemSelectionModel::::SingleSelection)
    
    检查您的QObject::connect是否工作正常:

    if (!connect(ui->listPorts->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSelectionChanged()))) 
         qDebug() << "Something wrong :(";
    
    if(!connect(ui->listPorts->selectionModel(),SIGNAL(selectionChanged(QItemSelection,QItemSelection)),this,SLOT(handleSelectionChanged())
    
    qDebug()很可能您没有更改选择,而是更改了当前/活动项。连接到激活的
    (const QModelIndex&index)
    信号。

    我发现了,这很愚蠢


    当一个新项目被添加到列表中时,我正在调用
    listPorts
    上的
    setModel()。我怀疑有更好的方法来处理更改,因此我将尝试修复该问题,但现在,每次更改模型时,我都会重新连接。

    不幸的是,这些似乎都不是原因。我已经交替尝试currentChanged和selectionChanged,两者都返回true,但都没有触发函数。handleSelectionChanged被定义为公共插槽,并与其他信号一起工作。默认选择模式为SingleSelection。连接似乎正在工作。常见问题是,您应该在初始化列表的模型后连接信号/插槽。