c++ - 将 Qlistview 限制为最多 1 个选定项目

标签 c++ linux qt

如果用户的选择多于 1 并且包括第一项,我会尝试强制程序选择 QListview 中的第一项(并且只有它)。 selectionMode 标志是多选,这意味着用户可以在 listview 中选择多个项目。

下面是我的代码:

void RealPlay::when_allchannel_selected
    (const QItemSelection &selected,
     const QItemSelection &deselected)
{

    // if the selected is the same with deseleted then
    //     just return, this is not necessary
    QModelIndexList selectedlist = selected.indexes();
    for(int i =0 ; i < selectedlist.length();++i)
    {
        if(!deselected.contains(selectedlist.at(i)))
        {
            break;
        }
        return;
    }

// channelmodel                QStandardItemModel
// selectedchannels            QItemSelectionModel
// ui->listView_channel        QListView

    //this is the first item that I want to select
    QModelIndex firstiteminchannelview =
        channelmodel->indexFromItem(channelmodel->item(0));

    if(selectedchannels->isSelected(firstiteminchannelview)
        && (selectedchannels->selectedIndexes().length()>1))
    {
        selectedchannels->reset();
        selectedchannels->select(firstiteminchannelview,\
             QItemSelectionModel::Select);
        //return;
    }

    //..
}

在构造函数中:

connect
(selectedchannels,
  SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),
  this,
  SLOT(when_allchannel_selected(const QItemSelection &,const QItemSelection &)));

但是这段代码不起作用。它只取消选择用户在选择第一项之前所做的最后选择,而不是取消选择除第一项以外的所有其他项目。我该怎么做?

其他问题:

  1. QItemSelectionQItemSelectionModel中的索引是否与QStandardItemModel中的索引相同?

比如如果 QStandardItemModel 中第一项的索引是 0,那么如果它被选中,无论序列是什么,索引仍然是 0QItemSelectionQItemSelectionModel 中。 (好像网上的资料暗示他们是一样的..)

  1. reset() 方法似乎有效。但为什么我仍然可以在 ListView 中看到多个选择?

最佳答案

事实证明我应该使用 QItemSelectionModel 的 select() 方法而不是 reset() 方法。以下是有效的代码。

if(selectedchannels->isSelected(firstiteminchannelview) && (selectedchannels->selectedIndexes().length()>1))
{
    //selectedchannels->reset();
    QModelIndex top = channelmodel->index(1,0);
    QModelIndex bottom = channelmodel->index(channelmodel->rowCount()-1,0);
    QItemSelection selection(top, bottom);
    selectedchannels->select(selection,QItemSelectionModel::Deselect);
    selectedchannels->select(firstiteminchannelview,QItemSelectionModel::Select);
    //return;
}

关于c++ - 将 Qlistview 限制为最多 1 个选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981289/

相关文章:

c++ - 如何通过哈希匹配boost multi_index_container中的nocase c字符串

c++ - this->func() 和 func() 的语法之间有什么细微差别吗?

python - numpy undefined symbol : PyFPE_jbuf

c++ - std::async 将创建和异步执行的最大线程数是多少?

linux - linux命令返回的退出状态1的含义

c++ - 将 std::vector emplace_back() 与 std::pair 与构造函数初始化列表一起使用

qt - 当 QGraphicsScene 中宽度减小到 200 以下时,x,y 点会发生移动

android - 如何在Android QT 中播放音频文件?

c++ - Qt 在 QtWebEngine View 中显示 QImage 或像素图(从 C++ 到 HTML)

c++ - 午餐期间游戏的代码挑战问题