如何在编程中获取QTableWidgetItem的边距宽度

How to programatically get the margin width of a QTableWidgetItem?

本文关键字:QTableWidgetItem 获取 编程      更新时间:2023-10-16

我认为标题是自身的说话:给定一个QTableWidget,带有setItem成员函数添加的项目,我想知道每个项目的余量是多少。特别是,我想要这些单元格中左边缘的宽度。

我已经准备了一个示例计算文本余量(项目矩形和文本内容矩形之间的空间),用户单击:

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();
}

编辑

要计算表单元边框和文本像素之间的精确空间,您必须使用QFontMetrics类。

请参阅QFontMetrics::leftBearing()QFontMetrics::tightBoundingRect()

相关文章:
  • 没有找到相关文章