C++ - QListWidget select first item

北慕城南 提交于 2021-02-11 04:33:45

问题


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...


回答1:


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


来源:https://stackoverflow.com/questions/18596260/c-qlistwidget-select-first-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!