qtqlistwidgetqttest

QListWidget doesn't recognize signals from QTest::mouseDClick


I am trying to use QTest to test UI interactions with a QListWidget. Interactions made from a simple click work fine (QTest::mouseClick()) but interactions from a double click do not (QTest::mouseDClick()).

Here is simplified code sample to reproduce the issue :

Dialog.h

class UILIBSHARED_EXPORT Dialog : public QDialog
{
    Q_OBJECT

  public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

    int doubleClickCount = 0;
    QString lastItemClicked = "";

    QListWidget* GetListW();

  private slots:
    void on_listWidget_doubleClicked(const QModelIndex &index);

  public:
    Ui::Dialog *ui;
};

Dialog.cpp

QListWidget*Dialog::GetListW()
{
  return ui->listWidget;
}

void Dialog::on_listWidget_doubleClicked(const QModelIndex &index)
{
  lastItemClicked = ui->listWidget->item(index.row())->text();
  ++doubleClickCount;
}

And the test class :

class DoubleClickTest : public QObject
{
Q_OBJECT

  public:
    DoubleClickTest();

  private Q_SLOTS:
    void testDoubleClick();
};

void DoubleClickTest::testDoubleClick()
{
  Dialog dialog;
  dialog.show();

  QListWidgetItem* item = dialog.GetListW()->item(1);
  QRect rect = dialog.GetListW()->visualItemRect(item);

  QTest::mouseDClick(dialog.GetListW()->viewport(), Qt::LeftButton, Qt::KeyboardModifiers(), rect.center());

  QCOMPARE(dialog.doubleClickCount, 1);
}

I checked the dialog manually and the slot is called as expected.


Solution

  • I know this is an old topic but I have encountered the same behaviour with a QTreeView and have passed some hours to find a workaround, so I think it can be useful for someone else.

    Using QTest, the signal doubleClicked is never emitted due to a part of code in sources of Qt I do not understand (qtreeview.cpp, line 1934 with Qt 5.12.1, or for others, in qabstractitemview.cpp line 1952). I don't know if it is a bug or not.

    To avoid this strange code, I just added a call to QTest::mouseClick before the call to QTest::mouseDClick with the same parameters. It worked for me because my QTreeView do nothing particular on a simple click, but it can distort tests in another case.

    If anyone has a better solution I take it !