1

In my QMainWindow Constructor I read a database and fill my QListWidget with the items. Apparently there is no item selected so I have to do it on my own. I also have a slot which will be called when I click on an item in the list.

I tried setCurrentRow( const int ) but if I do so the slot won't be called. I've seen the function setCurrentIndex( const QModelIndex & ) but I'm not familiar with the QModelIndex.

How do I tell my QListWidget to select the first item and call the on_list_clicked(const QModelIndex& index) slot?

Edit: Also, I cannot use any other slot than clicked because currentRowChanged(int) and itemSelectionChanged() both make my program crash when I remove a certain index from the list.

So somehow I need to perform a click on the list...

Davlog
  • 2,162
  • 8
  • 36
  • 60
  • Why not call setCurrentRow() and emit on_list_clicked(const QModelIndex& index) from your constructor? I.e., call QListWidget::currentItemChanged() after QListWidget::setCurrentItem. – sashoalm Sep 03 '13 at 17:43
  • @sashoalm well I could emit it but I need a QModelIndex for it. And that's the problem, I don't know how to create a QModelIndex the correct way... tried everything but it won't compile. – Davlog Sep 03 '13 at 18:07

1 Answers1

5

Calling setCurrentRow() emits the signal currentRowChanged(), which accepts an int instead of a QModelIndex.

Simply connect to that signal instead of to itemSelectionChanged().

Sample code:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->listWidget->setCurrentRow(1);
}

void MainWindow::on_listWidget_currentRowChanged(int currentRow)
{
    qDebug() << currentRow;
}
sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • I can't. When I remove a certain item from the list the program crashes. I have a QList which holds the information from a database. The row in the QListWidget is the current item in QList. When I change a row I want this information to be displayed in a few labels etc. So when I remove an item from the QList, then remove it from the QListWidget it tries to display the information of a row which may not exist anymore and causes a crash. – Davlog Sep 03 '13 at 18:35
  • Nevermind, thank you. I somehow messed up at some point, fixed it. Now your suggest using currentRow works. :) Thanks a lot. – Davlog Sep 03 '13 at 18:45