1

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.

Mickaël C. Guimarães
  • 1,020
  • 2
  • 14
  • 32

1 Answers1

3

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 !

  • I confirm this hack works on Windows (not my choice to use this abomination :/) as well. – pptaszni Nov 02 '21 at 16:00
  • Just to add some context, looks like the reason this happens is because it first checks if whatever you are trying to select is enabled. I can't really be bothered to continue through the source code to confirm what the means, but it seems like one click enables it and the second click actually performs the double click on the cell, which is why you need 2 events – The Elemental of Destruction Mar 23 '22 at 05:41