【问题标题】:Style sheet is appliped to the cells in QGridLayout instead of the parent container样式表应用于 QGridLayout 中的单元格而不是父容器
【发布时间】:2014-08-04 20:52:29
【问题描述】:

我继承了 QWidget 来创建一个名为(比如说..)TaskBox 的类。
我已将 QGridLayout 应用到我的 TaskBox。
布局由几个 QLabels 组成。

我通过设置样式表更改了任务框的背景颜色。
现在看起来像这样:

这就是我想要的,我很满意。

问题是,我想将 Q_OBJECT 宏添加到 TaskBox 类。 (因为我需要用到信号和槽)

添加Q_OBJECT宏后,我的TaskBox对象变成这样:

看起来样式表在 QGridLayout 中被分解为单元格。

这是我的 TaskBox 类:

class TaskBox : public QWidget{

Q_OBJECT

public:


    QLabel * title;
    QLabel * description;
    QGridLayout * layout;


   TaskBox(){

       layout = new QGridLayout();

       setRandomColor();   //Function is available below


       title = new QLabel("Something");
       title->setStyleSheet("color:white;");


       description = new QLabel("Something again");
       description->setStyleSheet("color:white;");


       layout->addWidget(title, 0,0);
       layout->addWidget(description,1,0);


       layout->setColumnStretch(0,2);
       layout->setColumnStretch(1,1);

       setLayout(layout);


   }


   void setRandomColor(){

        setStyleSheet("border-radius: 5px;background-color:rgb(" + QString::number((rand() % 255)) + "," + QString::number((rand() % 255)) + "," + QString::number((rand() % 255)) + ");");
   }


};

我不明白发生了什么。
感谢您的任何帮助!

【问题讨论】:

    标签: qt signals-slots moc qlayout


    【解决方案1】:

    当您继承QWidget 时,您需要覆盖paintEvent 函数以使样式表正常工作。

    你应该这样做:

    void CustomWidget::paintEvent(QPaintEvent *)
     {
         QStyleOption opt;
         opt.init(this);
         QPainter p(this);
         style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
     }
    

    【讨论】:

    • 这到底是做什么的?我从来没有想过使用样式表需要自定义paintEvent
    • @yankee2905 查看the qt docs。看关于QWidget的部分。
    【解决方案2】:

    尝试使用属性名称来消除您设置样式表的歧义

    在你的 TaskBox 构造函数中:

    setProperty("taskbox", true);
    

    然后:

       void setRandomColor(){
    
            setStyleSheet("*[taskbox=\"true\"] {border-radius: 5px;background-color:rgb(" + QString::number((rand() % 255)) + "," + QString::number((rand() % 255)) + "," + QString::number((rand() % 255)) + ");}");
       }
    

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 2014-12-24
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      相关资源
      最近更新 更多