QT QTableWidget表格控件单元格添加其他控件的万能方法

1、在单元格添加控件(以QLabel 为例)

    QWidget *pWidget = new QWidget(ui->devsViewTableWidget);
    QHBoxLayout *pLayout = new QHBoxLayout(ui->devsViewTableWidget);
    pLayout->setMargin(0);
    QLabel *pLabel = new QLabel(ui->devsViewTableWidget);
    pLabel->setObjectName("pLabel");
    pLabel->setFixedSize(16, 16);
    pLabel->setStyleSheet(QString("background:rgb(%1,%2,%3)").arg((devInfo->tSetInfo.u8Red == PTU_TEXT_COLOUR_USE) ? 255 : 0).arg((devInfo->tSetInfo.u8Green == PTU_TEXT_COLOUR_USE) ? 255 : 0).arg((devInfo->tSetInfo.u8Blue == PTU_TEXT_COLOUR_USE) ? 255 : 0));
    pLayout->addWidget(pLabel);
    pWidget->setLayout(pLayout);
    ui->TableWidget->setCellWidget(ui->devsViewTableWidget->rowCount() - 1, 10, pWidget);

2、获取单元格控件(以QLabel 为例)

    QWidget *pWidget = ui->TableWidget->cellWidget(i, 10);
    if (pWidget)
    {
        QLabel *pLabel = pWidget->findChild("pLabel");
        if (pLabel) {
            pLabel->setStyleSheet(QString("background:rgb(%1,%2,%3)").arg((devInfo->tSetInfo.u8Red == PTU_TEXT_COLOUR_USE) ? 255 : 0).arg((devInfo->tSetInfo.u8Green == PTU_TEXT_COLOUR_USE) ? 255 : 0).arg((devInfo->tSetInfo.u8Blue == PTU_TEXT_COLOUR_USE) ? 255 : 0));
         }
    }

你可能感兴趣的:(qt,开发语言)