- objective-c - iOS 5 : Can you override UIAppearance customisations in specific classes?
- iphone - 如何将 CGFontRef 转换为 UIFont?
- ios - 以编程方式关闭标记的信息窗口 google maps iOS
- ios - Xcode 5 - 尝试验证存档时出现 "No application records were found"
我将 QTreeView 子类化,我有两列,其中有复选框。我想设置两个不同的图像:一个用于第一列,另一个用于第二列。我知道我可以更改样式表中的图像:
QTreeView::indicator:checked{
image: url(:/checked);
}
QTreeView::indicator:unchecked{
image: url(:/unchecked);
}
但它会更改 TreeView 中的所有复选框。有没有办法用样式表来完成,还是我需要使用委托(delegate)?
最佳答案
简短回答:样式表不能做到这一点(据我所知)。它们在 Qt 中是一个非常不成熟的特性,而且似乎也没有对它们进行开发。
你可以做什么:
您不能为列或元素分配属性,也不能通过索引访问列。
但是您可以使用一些伪状态选择器,例如 :first
、:middle
和 :last
:
QTreeView::indicator:first:checked{
background: red;
}
QTreeView::indicator:middle:checked{
background: blue;
}
QTreeView::indicator:unchecked{
background: lightgray;
}
为了简单起见,我使用了颜色而不是图像。但是请注意,这些伪状态是实际当前可见的状态,因此如果允许用户对列重新排序,则列的样式可能会更改。例如,如果用户拖动其中一个 :middle
列并将其放在末尾,则该框将不再是蓝色。
您可以使用 Qt::DecorationRole
伪造它。
为此,您必须通过继承 QTreeView
或安装 event filter 来接收 mousePressEvent
.然后,当用户单击图标区域时,您可以更改图标(通过 Qt::DecorationRole
+ emit dataChanged()
)。
这当然不适用于键盘。
子类 QStyledItemDelegate
并覆盖 paint()
,就像您建议的那样。
如果您正在创建一个样式繁多的应用程序,您可能迟早要创建一个自定义样式。样式表只是不支持某些功能。
为此,子类 QProxyStyle
, 如果 QStyle::PE_IndicatorViewItemCheck
通过,则重写 drawPrimitive
并处理绘图。您还将收到一个 QStyleOptionViewItem
,其中包含一些有用的属性,例如 checkState
、features
(包含 QStyleOptionViewItem::HasCheckIndicator
如果有复选框),当然还有 index
,这样您就可以确定要绘制哪种复选框。
void MyItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyledItemDelegate::paint(painter, option, index);
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
const QWidget *widget = option.widget;
QStyle *style = widget ? widget->style() : QApplication::style();
QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &opt, widget);
drawCheckBox(painter, checkRect, opt.checkState, index);
}
void MyItemDelegate::drawCheckBox(QPainter * painter, const QRect & checkRect, Qt::CheckState checkState, const QModelIndex & index) const
{
if (checkState == Qt::Checked)
{
switch (index.column())
{
case 0:
painter->fillRect(checkRect, Qt::red);
break;
default:
painter->fillRect(checkRect, Qt::blue);
}
}
else
{
painter->fillRect(checkRect, Qt::lightGray);
}
}
这个例子简单快捷。只需在 QStyledItemDelegate 绘制的复选框上绘制即可。但是,需要您填满整个方框,否则将显示原件。
您可以尝试使用 QStyledItemDelegate 绘制除复选框以外的任何内容,然后再绘制复选框,但这有点难,如果您不想在上面花费太多时间,会给您留下一些小的绘图工件.
void MyStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption * opt, QPainter * p, const QWidget * w) const
{
if (pe == QStyle::PE_IndicatorViewItemCheck)
{
const QStyleOptionViewItem * o = static_cast<const QStyleOptionViewItem *>(opt);
drawCheckBox(p, opt->rect, o->checkState, o->index);
return;
}
QProxyStyle::drawPrimitive(pe, opt, p, w);
}
drawCheckBox()
函数与第一个示例相同。如您所见,这种方式更简单、更干净并且没有任何缺点。您可以在全局范围内应用样式,也可以仅为单个小部件应用样式。
关于css - 在 QTreeView 中为不同的复选框设置不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46790114/
我是一名优秀的程序员,十分优秀!