Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 859
rmweiss Avatar asked Oct 15 '25 03:10

rmweiss


1 Answers

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
like image 121
eyllanesc Avatar answered Oct 16 '25 17:10

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!