2015-08-16 83 views
1

我有一个QTableView工作得很好,第一列包含一些缩略图,在此列的每个单元格中,缩略图都是垂直居中的,但不是水平居中的。在QTableView单元的中心绘制QPixmap

我真的需要使用委托吗? 如果是,如何使用QStyledItemDelegate水平居中它们?

回答

2

自己画画是没有必要的,但一个自定义的代表 - 是。样式的项目代理使用样式的控件元素绘图代码绘制CE_ItemViewItem - 请参阅the source code for Qt 5.5.0。绘图代码将风格选项的decorationAlignment成员考虑在内。不幸的是,没有数据角色可以将这种对齐传递给样式的实现。相反,你必须覆盖在您的代理对齐:

class DecorationAligningDelegate : public QStyledItemDelegate { 
    Q_OBJECT 
    Qt::Alignment const m_alignment; 
public: 
    explicit DecorationAligningDelegate(Qt::Alignment alignment, QObject * parent = 0) : 
    QStyledItemDelegate(parent), m_alignment(alignment) {} 
    Qt::Alignment alignment() const { return m_alignment; } 
    void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { 
    auto opt = option; 
    opt.decorationAlignment = m_alignment; 
    QStyledItemDelegate::paint(painter, opt, index); 
    } 
}; 

然后,居中缩略图:

view.setItemDelegateForColumn(0, 
    new DecorationAligningDelegate(Qt::AlignHCenter, &view)); 
//or 
view->setItemDelegateForColumn(0, 
    new DecorationAligningDelegate(Qt::AlignHCenter, view)); 

如果你真的想自己画这一切,即使它是不必要的,矩形被选项目(option.rect)。要绘制在该项目的矩形中心的像素图,你可以做如下:

QStyleOption option; 
QPixmap pix; 
QPainter painter; 
... 
painter.save(); 
auto loc = option.rect.center() - pix.rect().center() 
painter.drawPixmap(loc, pix); 
painter.restore(); 
+0

所以,我必须使用委托? –

+0

@MohamedAnwer是的,你这样做,但委托是微不足道的,不会自己画任何东西。我已经展示了完成这种对齐的委托的完整源代码,以及如何将其设置在所需列上。对于Qt的视图和样式代码中的遗漏来说,这是一个简单的解决方法。 –

+0

我做了第一个代码片段,并且垂直对齐已消失,并且仍然没有水平对齐,我将Qt :: AlignHCenter更改为(Qt :: AlignHCenter | Qt :: AlignVCenter),并且垂直对齐再次出现,但仍然不是水平对齐, 你现在觉得怎么样? –

1

构建自己的代表和继承QStyledItemDelegate。重写paint方法。

然后做这样的事情:

void 
MyDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, 
          const QModelIndex& index) const 
{ 

    QPixmap pixmap; 
    pixmap.load("Your pixmap file path"); 
    pixmap = pixmap.scaled(option.rect.width(), option.rect.height(), Qt::KeepAspectRatio); 

    // Position our pixmap 
    const int x = option.rect.center().x() - pixmap.rect().width()/2; 
    const int y = option.rect.center().y() - pixmap.rect().height()/2; 

    if (option.state & QStyle::State_Selected) { 
     painter->fillRect(option.rect, option.palette.highlight());   
    } 

    painter->drawPixmap(QRect(x, y, pixmap.rect().width(), pixmap.rect().height()), pixmap); 

}