我在代码中使用了QGridLayout
,并且想将我的自定义窗口小部件添加到gridlayout中,但无法与addWidget(CustomWidget*)
一起使用。
这在带有Visual Studio 2013和Qt5.6.3。的Windows10上运行。
// *.h
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
private:
Ui::MainWindow ui;
};
class CustomWidget : public QWidget {
Q_OBJECT
public:
CustomWidget(QWidget *parent = Q_NULLPTR) : QWidget(parent) {}
~CustomWidget() {}
};
// *.cpp
// when i use CustomWidget
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
ui.setupUi(this);
QWidget *grid = new QWidget(this);
grid->setStyleSheet("background:pink;");
QGridLayout *layout = new QGridLayout(grid);
layout->setMargin(0);
layout->setSpacing(0);
grid->setLayout(layout);
grid->setGeometry(500, 150, 240, 180);
// following code is not working, when run this program,
// i can only see the 'grid' widget with pink background
CustomWidget *w = new CustomWidget(grid);
w->setStyleSheet("background:red;");
layout->addWidget(w, 0, 0);
}
// but if i use QWidget
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
ui.setupUi(this);
QWidget *grid = new QWidget(this);
grid->setStyleSheet("background:pink;");
QGridLayout *layout = new QGridLayout(grid);
layout->setMargin(0);
layout->setSpacing(0);
grid->setLayout(layout);
grid->setGeometry(500, 150, 240, 180);
// following code is working, when run this program,
// i can see the 'w' widget with red background
QWidget *w = new QWidget(grid);
w->setStyleSheet("background:red;");
layout->addWidget(w, 0, 0);
}
答案 0 :(得分:1)
如Qt的样式表参考中所述,将CSS样式应用于从QWidget继承的自定义窗口小部件需要以这种方式重新实现paintEvent()
:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
尽管按照文档所述,如果不这样做,您的自定义窗口小部件将仅支持background,background-clip和background-origin属性,因为这可能是一个错误。
>您可以在此处阅读有关内容:Qt Stylesheets reference在“样式控件列表”-> QWidget中。