2017-06-19 237 views
0

我以前问过这个问题,一个很棒的人让我对这个问题有一个体面的解决方法。不过,我希望看看是否有更好的解决方案。一个实际上阻止我的QListWidget完全转移。QListWidget水平滚动条导致选择离开视图

工作演示的例子

ListDemo zip文件 http://nexrem.com/test/ListDemo.zip

ListDemo cpp的代码

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    ui->setupUi(this); 

    myListWidget = new QListWidget(); 

    /* 
    * The signal-slot below is a temporary workaround for the shifting issue. 
    * This will ensure that the item selected remains in view, 
    * This is achieved by forcing the item to be in the center of the window; 
    * however, this has an undesired side-effect of visible 'jumping' as the list 
    * scrolls to center the item. 
    */ 
    //connect (myListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, 
    //   SLOT(scrollToItem(QListWidgetItem*))); 

    for (int i = 0; i <= 1000; ++i) 
    { 
     QListWidgetItem * myItem = new QListWidgetItem(myListWidget); 
     QString text(""); 
     for (int i = 0; i <= 40; ++i) 
     { 
      text.append("W"); 
     } 
     myItem->setText(text + QString::number(i)); 
    } 

    for (int i = 0; i <= 1000; ++i) 
    { 
     if (i%2) 
      myListWidget->item(i)->setHidden(true); 
    } 
    auto selected = myListWidget->selectedItems(); 
    if (selected.size() == 1) 
    { 
     myListWidget->scrollToItem(selected.front()); 
    } 
    setCentralWidget(myListWidget); 
} 


void MainWindow::scrollToItem(QListWidgetItem * item) 
{ 
    std::cout << "Scrolling to the item." << std::endl; 
    myListWidget->scrollToItem(item, QAbstractItemView::PositionAtCenter); 
} 

问题: 每当我有一个QListWidget与当前水平滚动条和隐藏的行,每当用户点击某个按钮时,我都会受到不希望的行为n项目,它从视图中消失,整个列表向下移动。 在上面的示例中,我隐藏了其他每一行,以演示此行为。

解决方法: 解决方法是使信号插槽连接强制将选定项滚动回视图并定位在中心位置。 请注意,我必须使用PositionAtCenter作为EnsureVisible不起作用。它认为该物品在视线之外时是可见的。 此变通办法是可以接受的;然而,当你的选择被迫定位在中心时,有可见的'跳跃'。这是一个不良的副作用。

在这一点上,我不确定这是否是一个QT错误(我认为水平滚动条不应该强制你的选择离开视图),或者我的代码缺少一些重要的东西。

解决方法: 按@ G.M.的评论,所有的失踪是myListWidget->setAutoScroll(false);

+0

看起来像一个QT错误。通过Qt 5.9.0,MSVC2015_x64进行了确认。如果没有隐藏的项目,则不会发生...您应该向QT报告 –

+1

[[myListWidget-> setAutoScroll(false)'](http://doc.qt.io/qt-5/qabstractitemview.html# autoScroll-prop)修复这个问题? –

+0

@ G.M。我不敢相信这件事很简单......但事实确实如此。请将其作为答案发布。 –

回答

1

正如在评论中提及...

为了防止自动滚屏上选择禁用autoScroll property。因此,在示例代码提供做...

myListWidget->setAutoScroll(false); 

注意,该酒店还拥有在将项目拖到列表视图,所以如果你想让你的列表视图充当下降网站,那么你会产生影响可能要在您获得QDragEnterEvent时重新启用此属性。