我有一個QTableView工作得很好,第一列包含一些縮略圖,在此列的每個單元格中,縮略圖都是垂直居中的,但不是水平居中的。在QTableView單元的中心繪製QPixmap
我真的需要使用委託嗎? 如果是,如何使用QStyledItemDelegate水平居中它們?
我有一個QTableView工作得很好,第一列包含一些縮略圖,在此列的每個單元格中,縮略圖都是垂直居中的,但不是水平居中的。在QTableView單元的中心繪製QPixmap
我真的需要使用委託嗎? 如果是,如何使用QStyledItemDelegate水平居中它們?
自己畫畫是沒有必要的,但一個自定義的代表 - 是。樣式的項目代理使用樣式的控件元素繪圖代碼繪製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();
構建自己的代表和繼承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);
}
所以,我必須使用委託? –
@MohamedAnwer是的,你這樣做,但委託是微不足道的,不會自己畫任何東西。我已經展示了完成這種對齊的委託的完整源代碼,以及如何將其設置在所需列上。對於Qt的視圖和樣式代碼中的遺漏來說,這是一個簡單的解決方法。 –
我做了第一個代碼片段,並且垂直對齊已消失,並且仍然沒有水平對齊,我將Qt :: AlignHCenter更改爲(Qt :: AlignHCenter | Qt :: AlignVCenter),並且垂直對齊再次出現,但仍然不是水平對齊, 你現在覺得怎麼樣? –