ui->tableWidget->setColumnCount(2);
QStringList header;
header << "name" <<"address";
//ui->tableWidget->setColumnWidth(0,30);//设置列宽
ui->tableWidget->setHorizontalHeaderLabels(header);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//单元格不可编辑
ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section {border-color: gray;border-width:1px; border-style: solid; height:22px}");//表头加边框
ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);//设置内容排列方式
ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
ui->tableWidget->verticalHeader()->setVisible(false);//设置垂直表头不可见
for(int i=0;i<4;i++)
{
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
ui->tableWidget->setItem(row,0,new QTableWidgetItem(QString::number(i)));
ui->tableWidget->item(row,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//设置内容居中
QFrame *frame = new QFrame(ui->tableWidget);
QPushButton *btn1 = new QPushButton(ui->tableWidget);
btn1->setText("...");
QLineEdit *lineEdit = new QLineEdit(ui->tableWidget);
QHBoxLayout *hLayout = new QHBoxLayout(frame);
hLayout->setMargin(0);
hLayout->addWidget(lineEdit);
hLayout->addWidget(btn1);
ui->tableWidget->setCellWidget(row,1,frame);
}
效果如下:
tips:
1.类似于listWidget,可以通过setData给每个item设值,也可以通过data取值,不过当item为控件时,不能通过setData设值,只能通过cellWidget得到该控件。
2.当程序报错Q_DECLARE_METATYPE时,一般是setData或者信号发送的数据类型得在头文件中用Q_DECLARE_METATYPE包一下。
Q_DECLARE_METATYPE(GsGeometryPtr)