使用qtbot.mouseClick选择QListWidgetItem

时间:2019-09-27 14:22:37

标签: python pytest pyside2 qlistwidget pytest-qt

如何使用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

有什么我想念的吗?

1 个答案:

答案 0 :(得分:2)

the docs指出:

  

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

     

返回项目上该项目所占据的视口上的矩形

(重点是我的)

位置中心相对于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(widget.viewport(), QtCore.Qt.LeftButton, pos=center)

    assert widget.currentRow() != 0