QTableWidget 中添加 QCheckBox控件

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
#include
#include

 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

 
    //设置3X3表格
    int Count = 3;
    ui->tableWidget->setRowCount(Count);
    ui->tableWidget->setColumnCount(Count);
    for(int row=0;row     {
        //提示:布局checkbox居中
        //1)将checkbox放到HBoxLayout中,将HBoxLayout设置居中
        //2)将HBoxLayout放到Widget中

        QCheckBox *checkBox =  new QCheckBox;
        QWidget *widget = new QWidget;
        QHBoxLayout *layout = new QHBoxLayout;
        layout->setMargin(2);
        layout->addWidget(checkBox);
        layout->setAlignment(Qt::AlignHCenter);
        widget->setLayout(layout);

 
        QTableWidgetItem *item1 = new QTableWidgetItem("AAA");
        QTableWidgetItem *item2 = new QTableWidgetItem("111");
        item1->setTextAlignment(Qt::AlignLeft);
        item2->setTextAlignment(Qt::AlignLeft);
        //添加widget到表格中
        ui->tableWidget->setCellWidget(row, 0, widget);
        ui->tableWidget->setItem(row,1,item1);
        ui->tableWidget->setItem(row,2,item2);
        ui->tableWidget->item(row,1)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidget->item(row,2)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    }
}

 
MainWindow::~MainWindow()
{
    delete ui;
}

你可能感兴趣的:(Qt)