In one of my projects I'm using a QTableWidget
in order to display some complex computational results. In order to increase the readability of the table I'm in need to display two aligned values inside of a single table cell.
Later on I want to customize the widget even more by using colors or arrows etc..
For this I derived from QStyledItemDelegate
and I called table ->setItemDelegate(new TwoNumbersDelegate)
on my QTableWidget
instance.
For some reasons the QFrame
is never display. I really tried everything. Strangely, a call to drawLine
gives some result, but only in the left cell on the top.
My idea is, that calling mFrame->render(...)
is not the correct way to do it, but what is the correct way?
My include file is:
#pragma once
#include <QStyledItemDelegate>
class QLabel;
class TwoNumbersDelegate : public QStyledItemDelegate {
public:
TwoNumbersDelegate(QObject* parent = nullptr);
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
private:
QLabel* mLeft;
QLabel* mRight;
QFrame* mFrame;
};
My cpp
-File is:
#include "TwoNumbersDelegate.h"
#include <QLabel>
#include <QPainter>
#include <QHBoxLayout>
TwoNumbersDelegate::TwoNumbersDelegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
mLeft = new QLabel("%1");
mRight = new QLabel("%2");
mFrame = new QFrame;
mFrame->setLayout(new QHBoxLayout);
mFrame->layout()->addWidget(mLeft);
mFrame->layout()->addWidget(mRight);
}
void TwoNumbersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
auto data=index.data(Qt::EditRole);
auto list=data.toList();
if (list.size() != 2) {
QStyledItemDelegate::paint(painter, option, index);
}
auto leftValue=list.at(0).toDouble();
auto rightValue=list.at(1).toDouble();
mLeft->setText(QString("%1").arg(leftValue));
mRight->setText(QString("%2").arg(rightValue));
mLeft->render(painter, QPoint(), option.rect);
painter->drawLine(4, 4, 7, 7); // Draws Line, but not in every cell of my table?
}
QSize TwoNumbersDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return mFrame->minimumSizeHint();
}
QStyledItemDelegate
is not derived fromQWidget
? How can it have a layout? Should I make it a QWidget? – DeleteQTextDocument::drawContents
to draw formatted content. Sample code may be found there: #16445058 – QuincyquindecagonQTextDocument
. It supports rich text formatting and Qt-html subset. So everything that you can output toQTextEdit
are available for fast rendering. So you may try something like this:<img src=":/myres/someicon.png" />
. – Quincyquindecagon