您可以在 QListWidget 顶部放置一个半透明的惰性小部件,并在选择更改时对其进行动画处理。但是您还需要一个委托来禁用正常选择指示器。
一个工作示例:
#include <QListWidget>
#include <QFrame>
#include <QPropertyAnimation>
#include <QStyledItemDelegate>
class RemoveSelectionDelegate : public QStyledItemDelegate {
public:
RemoveSelectionDelegate(QObject *parent = 0)
: QStyledItemDelegate(parent) {
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
// Call the original paint method with the selection state cleared
// to prevent painting the original selection background
QStyleOptionViewItemV4 optionV4 =
*qstyleoption_cast<const QStyleOptionViewItemV4 *>(&option);
optionV4.state &= ~QStyle::State_Selected;
QStyledItemDelegate::paint(painter, optionV4, index);
}
};
class ListWidget : public QListWidget {
Q_OBJECT
public:
ListWidget(QWidget *parent = 0)
: QListWidget(parent)
, selectionFrame(this)
, animation(&selectionFrame, "geometry") {
// Create a semi-transparent frame that doesn't interact with anything
selectionFrame.setAttribute(Qt::WA_TransparentForMouseEvents);
selectionFrame.setFocusPolicy(Qt::NoFocus);
// You can put your transparent image in that stylesheet
selectionFrame.setStyleSheet("background: solid rgba(0, 0, 125, 25%);");
selectionFrame.hide();
animation.setDuration(250);
animation.setEasingCurve(QEasingCurve::InOutBack);
connect(this,
SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)),
SLOT(updateSelection(QListWidgetItem*)) );
setItemDelegate(new RemoveSelectionDelegate(this));
}
private slots:
void resizeEvent(QResizeEvent *e) {
QListWidget::resizeEvent(e);
updateSelection(currentItem());
}
void updateSelection(QListWidgetItem* current) {
animation.stop();
if (!current) {
selectionFrame.hide();
return;
}
if (!selectionFrame.isVisible()) {
selectionFrame.setGeometry(visualItemRect(current));
selectionFrame.show();
return;
}
animation.setStartValue(selectionFrame.geometry());
animation.setEndValue(visualItemRect(current));
animation.start();
}
private:
QFrame selectionFrame;
QPropertyAnimation animation;
};