我正在开发一个应用程序,该应用程序需要在屏幕左侧有一个包含多个项目(文本)的菜单。我唯一想要可见的项目是实际文本和突出显示栏。我还想修改突出显示栏,以便: A。我可以为它设置动画,并将其从一个选择滑动到下一个选择 b.我可以使用带圆角的自定义像素图而不是默认的突出显示颜色
我尝试使用 QListWidget 和样式表并取得了一些成功,但我不认为可以使用此方法来圆化突出显示栏的角。我也不确定是否可以将栏从一项移动到下一项设置动画:
preset_list_view->setStyleSheet("QListView {color: rgb(230, 230, 230); background-color: rgba(0,0,0,0); border-style: none} QListView::item:selected {background-image: url(:/ui_resources/elements-preset_select/highlight_bar_270x30-black_bg.bmp)}");
我在网上查遍了,没有找到太多。有一些提到修改 QListWidget 的委托(delegate),但描述很模糊。我也不确定这是否能解决我的动画问题。
有什么想法吗?
最佳答案
您可以在 QListWidget 顶部放置一个半透明惰性小部件,并在选择更改时为其设置动画。 但您还需要一个委托(delegate)来禁用正常选择指示器。
一个工作示例:
#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;
};
关于qt - 如何自定义具有不同高亮条和间距的QListWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7274806/