4

How can I click on a QListWidgetItem with qtbot.mouseClick?

I tried it with the following code, but it fails on the final assert:

from PySide2 import QtWidgets, QtCore
import pytest


@pytest.fixture
def widget(qtbot):
    widget = QtWidgets.QListWidget()
    qtbot.addWidget(widget)
    for i in range(10):
        widget.addItem("Item %s" % (i + 1))
    widget.show()
    qtbot.wait_for_window_shown(widget)
    return widget


def test_aa_click_item(qtbot, widget):
    row = 7
    item = widget.item(row)

    rect = widget.visualItemRect(item)
    center = rect.center()

    assert widget.itemAt(center).text() == item.text()
    assert widget.currentRow() == 0

    qtbot.mouseClick(widget, QtCore.Qt.LeftButton, pos=center)

    assert widget.currentRow() != 0

Is there anything that I am missing?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
rmweiss
  • 716
  • 1
  • 6
  • 16

1 Answers1

2

As the docs points out:

QRect QListWidget::visualItemRect(const QListWidgetItem *item) const

Returns the rectangle on the viewport occupied by the item at item.

(emphasis mine)

The position center is with respect to the viewport() so you must use that widget to click:

def test_aa_click_item(qtbot, widget):
    row = 7
    item = widget.item(row)

    rect = widget.visualItemRect(item)
    center = rect.center()

    assert widget.itemAt(center).text() == item.text()
    assert widget.currentRow() == 0

    qtbot.mouseClick(widget.viewport(), QtCore.Qt.LeftButton, pos=center)

    assert widget.currentRow() != 0
eyllanesc
  • 235,170
  • 19
  • 170
  • 241