【问题标题】:Set widget background color设置小部件背景颜色
【发布时间】:2014-10-09 19:07:07
【问题描述】:

我在QTableWidgetCell中使用QCheckBox

QWidget *widget = new QWidget();
QCheckBox *checkBox = new QCheckBox();
QHBoxLayout *layout = new QHBoxLayout(widget);
layout->addWidget(checkBox);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
widget->setLayout(layout);
table->setCellWidget(0, 0, widget);

如何更改单元格背景?

【问题讨论】:

    标签: qt qtablewidget qcheckbox


    【解决方案1】:

    代码:

    widget->setStyleSheet("background-color: red");
    

    工作正常,但您需要为添加到表格中的每个容器小部件设置样式:

    因此,为了查看更改,您需要以下代码:

    QWidget *widget = new QWidget();
    widget->setStyleSheet("background-color: red");
    QCheckBox *checkBox = new QCheckBox();
    QHBoxLayout *layout = new QHBoxLayout(widget);
    layout->addWidget(checkBox);
    layout->setAlignment(Qt::AlignCenter);
    layout->setContentsMargins(0, 0, 0, 0);
    widget->setLayout(layout);
    
    QWidget *widget2 = new QWidget();
    widget2->setStyleSheet("background-color: red");
    QCheckBox *checkBox2 = new QCheckBox();
    QHBoxLayout *layout2 = new QHBoxLayout(widget2);
    layout2->addWidget(checkBox2);
    layout2->setAlignment(Qt::AlignCenter);
    layout2->setContentsMargins(0, 0, 0, 0);
    widget2->setLayout(layout);
    
    ui->tableWidget->setCellWidget(0, 0, widget);
    ui->tableWidget->setCellWidget(0, 1, widget2);
    

    结果将是:

    【讨论】:

    • 它有效。但只有最后一个背景更改单元格设置了背景。以前的单元格背景已恢复。
    【解决方案2】:

    你应该试试这个:

    checkBox->setStyleSheet("background-color: red;");
    

    如果您想更一般地指定它,请在 CSS 中编写 classtype 以指示层次结构中的哪个类应该处理该标志。这可能看起来像这样:

    QWidget { background-color: red; }
    

    【讨论】:

      【解决方案3】:

      如果要更改单元格背景,而不是小部件,请使用setBackground() 方法:

      QCheckBox *checkBox = new QCheckBox("example");
      QWidget *widget = new QWidget();
      QHBoxLayout *layout = new QHBoxLayout(widget);
      layout->addWidget(checkBox);
      layout->setAlignment(Qt::AlignCenter);
      layout->setContentsMargins(0, 0, 0, 0);
      widget->setLayout(layout);
      ui->tableWidget_2->setCellWidget(0,0,widget);
      ui->tableWidget_2->item(0, 0)->setBackground(Qt::red);//this line should be
      

      在这种情况下,您的所有单元格都将是红色的(复选框周围没有白线)。

      【讨论】:

      • ui->tableWidget_2->item(0, 0)->setBackground(Qt::red);很危险,因为 .setCellWidget 不会在该单元格上创建返回空指针的项目
      • 最后一行导致崩溃,因为item(0,0) 返回一个空指针。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2016-07-21
      相关资源
      最近更新 更多