rmweiss
rmweiss

Reputation: 716

Selecting QListWidgetItem with qtbot.mouseClick

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?

Upvotes: 4

Views: 983

Answers (1)

eyllanesc
eyllanesc

Reputation: 243945

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

Upvotes: 2

Related Questions