2016-12-19 21 views
2

私はタイトルがそれ自身のために話していると思う:の項目がsetItemメンバー機能によって追加されていると、各項目の余白が何であるか知りたい。特に、これらのセルには左余白の幅が必要です。QTableWidgetItemの余白の幅をプログラムで取得する方法は?

+0

セルテキストとセル境界の間のスペースを参照していますか? –

+0

はい。私はそれがいつも "マージン"が意味するものだと思った。 –

+0

'table.cellWidget(row、col) - > contentsMargins()。left()'を試したことがありますか? –

答えて

1

Iは、上の項目のユーザーのクリックのテキストマージン(項目矩形とテキスト内容長方形との間の空間)を計算するほとんどの例を調製した:

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

表のセル境界線とテキストピクセルの間には、QFontMetricsクラスを使用する必要があります。

QFontMetrics::leftBearing()およびQFontMetrics::tightBoundingRect()を参照してください。

+0

良いプログラムですが、計算に間隔がありません:左余白は常に0ですが、列の左端とテキストの開始点の間には目に見える隙間があります。 私は試しませんでしたが、楕円を得ることなく、列と同じ幅のテキストで列を塗りつぶすことはできません。テキストを折り返すために正確な計算が必要です。 また、テーブル自体から値を取得する方法があるはずですが、各アイテムの値は常に同じです(この場合は0)。 –

+0

文字の左マージンと一番左のピクセルの間隔は、実際には表のセルではなくフォントのプロパティです。 'QFontMetrics'を使ってギャップ幅を計算します。 – Tomas

関連する問題