Christopher Donham
Christopher Donham

Reputation: 131

Qt QFrame StyleSheet not working in MainWindow

I am struggling with a basic StyleSheet question. I am trying to apply a stylesheet to a QFrame within a MainWindow, and for some reason, the stylesheet is being ignored. This seems related to Qt Stylesheet for custom widget and Enable own widget for stylesheet, but I've tried adding a paintEvent and that did not help. Its gotta be something simple, but I can't see it. Can anyone help?

main.cpp:

#include <QApplication>
#include <QDebug>

#include "mainwindow.h"

int main(int argc, char *argv[]) {

  QApplication app(argc, argv);
  MainWindowDef mainWindow;
  mainWindow.show();
  return app.exec();
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtWidgets>

class MainWindowDef : public QMainWindow {
  Q_OBJECT

public:
  MainWindowDef(QWidget *parent = 0);

protected:
  void paintEvent(QPaintEvent *);
};

#endif

mainwindow.cpp:

#include <QDebug>

#include "mainwindow.h"

MainWindowDef::MainWindowDef(QWidget *parent) : QMainWindow(parent) {

  QFrame *frame = new QFrame;

  QVBoxLayout *layout = new QVBoxLayout;

  QPushButton *button = new QPushButton("Press");
  layout->addWidget(button);

  QString myStyle = QString( "QFrame {"
                 "border: 2px solid green;"
                 "border-radius: 4px;"
                 "padding: 2px"
                 "background-color: red;" 
                 "color: blue;"
                 "}");

  frame->setStyleSheet(myStyle);
  frame->setLayout(layout);
  frame->setAutoFillBackground(true);

  setCentralWidget(frame);
}

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

Upvotes: 1

Views: 1366

Answers (1)

Christopher Donham
Christopher Donham

Reputation: 131

I finally figured this out. It was missing a semicolon.

"padding: 2px"

should say:

"padding: 2px;"

Sigh.

Upvotes: 1

Related Questions