Problems with QTest::mouseClick on QListWidget

跟風遠走 提交于 2019-12-21 12:06:29

问题


I am trying to use QTest to do some testing. I have a QListWidget that I would like to click on to get a selection. But after the click, nothing is selected. Does anyone have any ideas?

Here is my test class

void TestGui::List() {
    TestDialog dlg;
    dlg.show ();

    // Click on the centre of the second object
    QListWidget *list = dlg.ListWidget ();
    QListWidgetItem *item = list->item ( 1 );
    QRect rect = list->visualItemRect ( item );
    QTest::mouseClick ( list, Qt::LeftButton, 0, rect.center() );

    // Check if something was selected
    QCOMPARE ( list->currentRow (), 1 );
    QVERIFY ( list->currentItem () != NULL );
    QCOMPARE ( list->currentItem ()->text (), QString ( "Two" ) );
}

Below is the testing class

class TestGui: public QObject {
    Q_OBJECT

private slots:
    void List();
};

And here is the TestDialog class used to display the problem

class TestDialog : public QDialog {
    Q_OBJECT

public:
    TestDialog ( QWidget *parent = NULL )
    : QDialog ( parent, Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint ) {
        QVBoxLayout *layout = new QVBoxLayout ( this );

        m_list = new QListWidget ( this );
        m_list->addItem ( "One" );
        m_list->addItem ( "Two" );
        m_list->addItem ( "Three" );
        m_list->addItem ( "Four" );
        layout->addWidget ( m_list );

        QPushButton *close_button = new QPushButton( "Close" );
        connect ( close_button, SIGNAL ( clicked () ), this, SLOT ( close () ) );
        layout->addWidget ( close_button );

        setWindowTitle( "Test" );
    }

    QListWidget *ListWidget ( void ) {
        return m_list;
    };

private:
    QListWidget *m_list;

}; // TestDialog

回答1:


After some more thought, it turns out that the click needs to be on the view widget and not the list itself. So the line should look like this

QTest::mouseClick ( list->viewport (), Qt::LeftButton, 0, rect.center() );

Thanks



来源:https://stackoverflow.com/questions/10728362/problems-with-qtestmouseclick-on-qlistwidget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!