How to set icon center in QTableView?

后端 未结 2 1887
轻奢々
轻奢々 2021-01-03 10:22
NetworkPageForm::NetworkPageForm(QWidget *parent) :
      QWidget(parent),
      ui(new Ui::NetworkPageForm),
      devicesModel(NULL)
{
      ui->setupUi(this);
         


        
相关标签:
2条回答
  • 2021-01-03 10:30

    There is no default way. You should implement your own QStyledItemDelegate.

    UPD: example added

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        Q_ASSERT(index.isValid());
    
        QStyleOptionViewItemV4 opt = option;
        initStyleOption(&opt, index);
        // disable default icon
        opt.icon = QIcon();
        // draw default item
        QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter, 0);
    
        const QRect r = option.rect;
    
        // get pixmap
        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QPixmap pix = icon.pixmap(r.size());
    
        // draw pixmap at center of item
        const QPoint p = QPoint((r.width() - pix.width())/2, (r.height() - pix.height())/2);
        painter->drawPixmap(r.topLeft() + p, pix);
    }
    
    0 讨论(0)
  • 2021-01-03 10:40

    It's no need to do it in delegate. The delegate will make your style sheet unavailable. You can paint the icon in the middle of a rectangle pixmap which is as same size as the cell, and return it in the QAbstractItemModel::data() function with Qt::DecorationRole. Like this:

    Qt::DecoratoinRole:
        QPixmap pixmap(w, h);  //w=cell width, h=cell
        pixmap.fill(Qt::transparent); // draw a transparent rectangle
        QPixmap iconPixmap(":/xx.png");
        QPainter painter(&pixmap);
        //Calculate the center coordinate x,y for iconPixmap
        painter.draw(x, y, iconWidth, iconHeight, iconPixmap);
        return pixmap;
    
    0 讨论(0)
提交回复
热议问题