8

我正在尝试使用 QTest 进行一些测试。我有一个 QListWidget,我想点击它来进行选择。但是点击之后,什么都没有被选中。有没有人有任何想法?

这是我的测试课

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" ) );
}

下面是测试类

class TestGui: public QObject {
    Q_OBJECT

private slots:
    void List();
};

这是用于显示问题的TestDialog类

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
4

1 回答 1

10

经过一番思考,事实证明点击需要在视图小部件上而不是列表本身上。所以这条线应该是这样的

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

谢谢

于 2012-05-24T10:40:20.727 回答