标签:
QListWidget在QListView::IconMode模式下,当条目可以移动时,如果发生部分或者全部重叠,那么点击其中一个QListWidgetItem,会同时选中重叠的QListWidgetItem,问题如下图:
但是我只想同时选择我点击的那个,解决这个问题,没有找到很好的方法。通过继承mousePressEvent事件来进行处理:
void ListWidget::mousePressEvent(QMouseEvent *event) { __super::mousePressEvent(event); QListWidgetItem *pItem = itemAt(event->pos()); if (pItem) { int iCount = count(); for (size_t i = 0; i < iCount; i++) { QListWidgetItem *p = item(i); if (!p) break; if (p != pItem) p->setSelected(false); else p->setSelected(true); } } }或者:
void ListWidget::mousePressEvent(QMouseEvent *event) { __super::mousePressEvent(event); QListWidgetItem *pItem = itemAt(event->pos()); if (pItem) { QList<QListWidgetItem *> pItems = selectedItems(); for (auto it = pItems.begin(); it != pItems.end(); it++) { if ((*it) != pItem) (*it)->setSelected(false); else (*it)->setSelected(true); } } }都可以满足要求。如果有人有更好的方法,请指导。
效果:
完整测试代码:
#ifndef LISTWIDGET_H #define LISTWIDGET_H #include <QtWidgets/QListWidget> class ListWidget : public QListWidget { Q_OBJECT public: ListWidget(QWidget *parent = 0); ~ListWidget(); protected: void mousePressEvent(QMouseEvent *event); private: }; #endif // LISTWIDGET_H
#include "listwidget.h" #include <QMouseEvent> ListWidget::ListWidget(QWidget *parent) : QListWidget(parent) { //添加Item QStringList strList = { "Item1", "Item2", "Item3", "Item4", "Item5" }; this->addItems(strList); this->setViewMode(QListView::IconMode); this->setResizeMode(QListView::Adjust); this->setIconSize(QSize(64, 64)); } ListWidget::~ListWidget() { } void ListWidget::mousePressEvent(QMouseEvent *event) { __super::mousePressEvent(event); QListWidgetItem *pItem = itemAt(event->pos()); if (pItem) { QList<QListWidgetItem *> pItems = selectedItems(); for (auto it = pItems.begin(); it != pItems.end(); it++) { if ((*it) != pItem) (*it)->setSelected(false); else (*it)->setSelected(true); } } } //void ListWidget::mousePressEvent(QMouseEvent *event) //{ // __super::mousePressEvent(event); // QListWidgetItem *pItem = itemAt(event->pos()); // if (pItem) // { // int iCount = count(); // for (size_t i = 0; i < iCount; i++) // { // QListWidgetItem *p = item(i); // if (!p) // break; // // if (p != pItem) // p->setSelected(false); // else // p->setSelected(true); // } // } //}
#include "listwidget.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); ListWidget w; w.show(); return a.exec(); }本文地址:http://blog.csdn.net/u011417605/article/details/50954779
交流QQ:1245178753
Qt学习之解决QListWidgetItem有重叠时,点一下全部选中的问题
标签:
原文地址:http://blog.csdn.net/u011417605/article/details/50954779