2013-02-13 925 views
6

在QtCreater中,我在我的項目中添加了一個表。在我的代碼中,我生成一些數據輸出到表中。我想在每行添加一個QCheckbox以允許選擇該行。表中的所有內容都是左對齊的,我怎樣才能使每一行的第一列中的這些複選框與中心對齊?Qt - 將複選框居中在QTable中

我使用添加QCheckbox

ui->data_table->setCellWidget(rowCount,0, new QCheckBox); 

回答

5

我通常使用的佈局,併爲這個容器構件。這是一個醜陋的解決方案,但它的工作原理:

QWidget * w = new QWidget(); 
QHBoxLayout *l = new QHBoxLayout(); 
l->setAlignment(Qt::AlignCenter); 
l->addWidget(<add your checkbox here>); 
w->setLayout(l); 
ui->data_table->setCellWidget(rowCount,0, w); 

所以基本上你將有:

Table Cell -> Widget -> Layout -> Checkbox 

你必須考慮,如果你將需要通過訪問表的複選框。

+0

看起來似乎應該更容易。我正在瀏覽文檔很長一段時間,試圖找到一個功能或做我想要的東西。但是你發佈的內容完美無瑕,但我從來沒有想過自己會這麼做。謝謝! – Mitch 2013-02-13 08:17:54

+0

它似乎不再適用於QT5。 – bismute 2017-11-21 02:45:34

5

它適用於我,但我的複選框沒有完全顯示。

要具有窗口小部件的完整視圖,在佈局中刪除邊距:

1-> setContentsMargins(0,0,0,0);

3

這是一個老的文章,但其實有實現這一目標的一個更容易和輕巧的方式,只要繼承QCheckBox並設置stylesheet

margin-left:50%; 
margin-right:50%; 
+0

Im在PyQt4中,這隻有在設置初始值時才起作用。也就是說,如果我調整列的大小,它不會繼續居中複選框,它只會在第一次創建時將其居中。 – Spencer 2017-11-17 04:11:14

6

兩個大拇指巴里Mavin!你甚至不需要繼承。

一行...

pCheckBox-> setStyleSheet( 「保證金左:50%;餘量右:50%;」);

完成!

+0

「margin:auto;」也適用。 – 2018-02-09 17:42:57

0
#if QT_VERSION < 0x046000 
#include <QCommonStyle> 
class MyStyle : public QCommonStyle { 
public: 
    QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const { 
    switch(subElement) { 
     case QStyle::SE_CheckBoxIndicator: { 
     QRect r = QCommonStyle::subElementRect(subElement, option, widget); 
     r.setRect((widget->width() - r.width())/2, r.top(), r.width(), r.height()); 
     return QRect(r); 
     } 
     default: return QCommonStyle::subElementRect(subElement, option, widget); 
    } 
    } 
}; 
#else 
#include <QProxyStyle> 
#include <QStyleFactory> 
class MyStyle: public QProxyStyle { 
public: 
    MyStyle():QProxyStyle(QStyleFactory::create("Fusion")) {} 
    QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const { 
    switch(subElement) { 
     case QStyle::SE_CheckBoxIndicator: { 
     QRect r = QProxyStyle::subElementRect(subElement, option, widget); 
     r.setRect((widget->width() - r.width())/2, r.top(), r.width(), r.height()); 
     return QRect(r); 
     } 
     default: return QProxyStyle::subElementRect(subElement, option, widget); 
    } 
    } 
}; 
#endif 

QCheckBox *box = new QCheckBox(); 
box->setStyle(new MyStyle());