2016-09-01 29 views
0

我有一個接口有兩個QListViews,其中左側決定什麼是顯示在右: layout而QListView selectionModel設置不發送的SelectionChanged信號

到右側更新列表,我有以下功能:

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()。它不會產生任何錯誤,它只是沒有做任何事情。有人能告訴我爲什麼嗎?

回答

0

我明白了,它很愚蠢。

當一個新項目被添加到列表中,我打電話setModel()listPorts,這當然打破了連接。我懷疑有更好的方法來處理這種變化,所以我會嘗試解決這個問題,但現在,每次模型改變時我都會重新連接。

1

連接看起來對我很好。你確定你沒有看到任何運行時錯誤?下面,幾件事情來檢查他們是否有幫助。

1)檢查您是否已將Q_OBJECT宏添加到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)測試,如果currentChanged信號通過連接它例如觸發handleCurrentChanged插槽。

+0

不幸的是,這些似乎都不是原因。我已經交替嘗試currentChanged和selectionChanged,都返回true,但都沒有觸發該函數。 – Magrias

1

更多鈔票錯誤:

  1. 是您的功能handleSelectionChanged()定義爲私有/公有槽?
  2. 是您的默認設置SelectionModeQAbstractItemView::NoSelection

試圖迫使單/多選:

ui->listPorts->setSelectionMode(QItemSelectionModel::::SingleSelection) 

檢查您的QObject :: Connect是正常工作:

if (!connect(ui->listPorts->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSelectionChanged()))) 
    qDebug() << "Something wrong :("; 
+0

handleSelectionChanged被定義爲一個公共插槽,並與其他信號一起工作。默認的SelectionMode是SingleSelection。連接似乎正在工作。 – Magrias

+0

常見問題,您應在初始化列表模型後連接信號/插槽。 – mohabouje

0

最有可能你不改變選擇,你正在改變當前/活動項目。改爲連接到activated(const QModelIndex &index)信號。