使用 qtbot.mouseClick 选择 QListWidgetItem

Selecting QListWidgetItem with qtbot.mouseClick

如何使用 qtbot.mouseClick 单击 QListWidgetItem?

我用下面的代码试过了,但它在最后的断言上失败了:

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

有什么我遗漏的吗?

正如the docs指出的那样:

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

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

(强调我的)

位置中心是相对于 viewport() 所以你必须使用那个小部件来点击:

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(<b>widget.viewport()</b>, QtCore.Qt.LeftButton, pos=center)

    assert widget.currentRow() != 0