Reputation: 7994
I think the title speaks for itself: Given a QTableWidget
with items added by the setItem
member function, I want to know what the margin is for each item. In particular, I want the width of the left margin in these cells.
Upvotes: 2
Views: 1633
Reputation: 2210
I have prepared a little example computing text margins (a space between item rectangle and text content rectangle) of an item users clicks on:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow mainWin;
QTableWidget* table = new QTableWidget(3, 3, &mainWin);
table->setItem(0, 0, new QTableWidgetItem("Item A"));
table->setItem(1, 0, new QTableWidgetItem("Item B"));
table->setItem(2, 0, new QTableWidgetItem("Item C"));
table->setItem(0, 1, new QTableWidgetItem("Item D"));
table->setItem(1, 1, new QTableWidgetItem("Item E"));
table->setItem(2, 1, new QTableWidgetItem("Item F"));
table->setItem(0, 2, new QTableWidgetItem("Item G"));
table->setItem(1, 2, new QTableWidgetItem("Item H"));
table->setItem(2, 2, new QTableWidgetItem("Item I"));
mainWin.setCentralWidget(table);
mainWin.show();
auto slot = [&table](QTableWidgetItem* item){
QStyleOptionViewItem option;
option.font = item->font();
option.fontMetrics = QFontMetrics(item->font());
if (item->textAlignment())
option.displayAlignment = static_cast<Qt::Alignment>(item->textAlignment());
else
option.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter; // default alignment
option.features |= QStyleOptionViewItem::HasDisplay;
option.text = item->text();
option.rect = table->visualItemRect(item);
// If your table cells contain also decorations or check-state indicators,
// you have to set also:
// option.features |= QStyleOptionViewItem::HasDecoration;
// option.icon = ...
// option.decorationSize = ...
QRect textRect = table->style()->subElementRect(QStyle::SE_ItemViewItemText, &option, nullptr);
double leftMargin = textRect.left() - option.rect.left();
double rightMargin = option.rect.right() - textRect.right();
double topMargin = textRect.top() - option.rect.top();
double bottomMargin = option.rect.bottom() - textRect.bottom();
qDebug() << leftMargin;
qDebug() << rightMargin;
qDebug() << topMargin;
qDebug() << bottomMargin;
};
QObject::connect(table, &QTableWidget::itemClicked, slot);
return app.exec();
}
EDIT
To compute an exact space between table cell border and the text pixels, you have to use a QFontMetrics
class.
See the QFontMetrics::leftBearing()
and QFontMetrics::tightBoundingRect()
.
Upvotes: 1