PDA

View Full Version : When windows focused and QListWidget had focus, first item selected, bug?



Douglish
30th April 2011, 18:07
Hi all,
If I have a QListWidget and I add for example two or more items, then I click to QListWidget to focus (but not by clicking to some item, just click somewhere else in the QListWidget) it, after that if window loses focus and again gains focus, first item of QListWidget is selected, is this a bug or expected behavior?



#include <QApplication>
#include <QMainWindow>
#include <QListWidget>
#include <QString>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>

int main(int argc, char **argv) {
QApplication app(argc, argv);
QMainWindow m_window;

QListWidget *m_listWidget = new QListWidget;
QHBoxLayout *m_layout = new QHBoxLayout;
QLineEdit *m_line = new QLineEdit;
QLabel *m_label = new QLabel;
QWidget *m_widget = new QWidget;

QObject::connect(m_listWidget, SIGNAL(currentRowChanged(int)), m_label, SLOT(setNum(int)));

m_listWidget->addItem("One");
m_listWidget->addItem("Two");

m_layout->addWidget(m_line);
m_layout->addWidget(m_label);
m_layout->addWidget(m_listWidget);

m_widget->setLayout(m_layout);
m_window.setCentralWidget(m_widget);

m_window.show();
app.exec();
return 0;
}



If you compile it and run, then click on the list widget, but not on some item, then switch to another window and back, now first item is selected and currentRowChanged is emitted. (This represents QLabel next to QLineEdit).

QLineEdit is there only because to avoid focus of QListWidget on start of application.

borzh62
11th November 2015, 14:14
I have same issue, I think this is a bug.
Workaround for this is to use selectionChanged(QItemSelection,QItemSelection) instead of currentRowChanged(QModelIndex,QModelIndex) and use next code:



void YourClass::selectionChangedSlot(const QItemSelection& selection, const QItemSelection&)
{
QModelIndexList selected = selection.indexes();
int row = selected.size() ? selected.first().row() : -1;
...
}