一. 问题现象
在QListWidget设置为QListVIew::IconMode时,会偶尔出现自定义的QWidget作为QListWidget的Item位置出现偏移,效果如下(其中有一个出现了位置偏移)
ui->listWidget_Video->setViewMode(QListView::IconMode);
void CVideoScreenShotListWnd::AddWidget(const QString& qstrTaskId, const QString& qstrVideoTag, const SimpleCameraInfo& stuCam)
{
CVideoScreenShotWnd* pWidget = new(std::nothrow) CVideoScreenShotWnd(this);
pWidget->SetParam(qstrTaskId, qstrVideoTag, stuCam);
QListWidgetItem *item = new QListWidgetItem();
item->setSizeHint(QSize(136,112));//136,112
ui->listWidget_Video->addItem(item);
ui->listWidget_Video->setItemWidget(item, pWidget);
}
二. 问题原因及解决办法
追代码发现是在Item Layout过程中,代理中updateEditorGeometry采用的style计算的 位置有问题
QAbstractItemDelegate *delegate = d->delegateForIndex(index);
if (delegate)
delegate->updateEditorGeometry(editor, option, index);
所以为QListWidget设置个Delegate,覆写updateEditorGeometry方法(不手动给QListWidget设置Delegate时,QT也会自动给QListWidget设置默认的Delegate)
CTestListWidget.cpp
ui->listWidget_Video->setResizeMode(QListView::Adjust);
ui->listWidget_Video->setViewMode(QListView::IconMode);
ui->listWidget_Video->setSpacing(10);
CVideoScreenShotDelegate *delegate = new CVideoScreenShotDelegate(this);
ui->listWidget_Video->setItemDelegate(delegate);
VideoScreenShotDelegate.h
#pragma once
#include <QStyledItemDelegate>
class CVideoScreenShotDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
CVideoScreenShotDelegate(QWidget *parent = nullptr);
virtual ~CVideoScreenShotDelegate();
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
VideoScreenShotDelegate.cpp
#include "VideoScreenShotDelegate.h"
CVideoScreenShotDelegate::CVideoScreenShotDelegate(QWidget *parent)
{
}
CVideoScreenShotDelegate::~CVideoScreenShotDelegate()
{
}
void CVideoScreenShotDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
// option.rect属性中保存了Item的位置
editor->setGeometry(option.rect);
}
相关资料:
QListWidget自定义item的两种方式(二)——使用QWidget作为item
QListWidget自定义item的两种方式(一)——使用Delegate