2016-10-27 110 views
0

我正在製作一個Qt5.7應用程序,其中我從文件中讀取東西后填入QListView。這是它的確切代碼。Qt5:獲取在列表視圖中單擊的項目的值

QStringListModel *model; 
model = new QStringListModel(this); 
model->setStringList(stringList); //stringList has a list of strings 
ui->listView->setModel(model); 
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers); //To disable editing 

現在,這個列表在我設置的QListView中顯示得很好。我現在需要做的是獲得已被雙擊的字符串,並在其他地方使用該值。我如何實現這一目標?

我想這樣做是給聽衆這樣

... // the rest of the code 
connect(ui->listView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(fetch())); 
... 

然後我具備的功能fetch

void Window::fetch() { 
    qDebug() << "Something was clicked!"; 
    QObject *s = sender(); 
    qDebug() << s->objectName(); 
} 

連接到QListView然而objectName()函數返回「ListView控件」,而不是ListView控件項目或索引。

+1

您應該添加'QModelIndex'作爲參數到您的插槽並使用該插槽。 – Hayt

回答

1

的信號已經爲您提供了其獲得點擊,QModelIndex

所以您應將插槽改成這樣:

void Window::fetch (QModelIndex index) 
{ 
.... 

QModelIndex現在有一列和行屬性。由於列表中沒有列,因此您在該行中進行操作。這是點擊項目的索引。

//get model and cast to QStringListModel 
QStringListModel* listModel= qobject_cast<QStringListModel*>(ui->listView->model()); 
//get value at row() 
QString value = listModel->stringList().at(index.row()); 
+0

工作。謝謝! – Zeokav

0

您應該添加索引作爲您的插槽的參數。您可以使用該索引訪問列表

您的代碼應該是這樣的。

void Window::fetch (QModelIndex index) { /* Do some thing you want to do*/ }

相關問題