Reputation: 122
I create a very simple subclass of QWidget like this:
class WorldView : public QWidget
{
Q_OBJECT
public:
explicit WorldView(QWidget *parent = 0);
signals:
public slots:
};
WorldView::WorldView(QWidget *parent) : QWidget(parent)
{
}
I create an instance of it in main window like this:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
virtual void resizeEvent(QResizeEvent* event) override;
private:
WorldView* _worldView;
};
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
_worldView = new WorldView(this);
_worldView->setStyleSheet(QString("* {background-color : black}"));
}
MainWindow::~MainWindow()
{
delete _worldView;
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
_worldView->resize(size());
}
But the widget does not show as expected.
I have tried to call show()
, but it still doesn't show.
The weird thing is that when I replace WorldView
with QWidget
, the widget shows.
I don't know why.
Upvotes: 1
Views: 1706
Reputation: 22724
Because stylesheets don't work that way for custom QWidget subclasses.
From https://doc.qt.io/qt-5/stylesheet-reference.html :
QWidget
Supports only the background, background-clip and background-origin properties.
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
void CustomWidget::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
The above code is a no-operation if there is no stylesheet set.
Warning: Make sure you define the Q_OBJECT macro for your custom widget.
(And, in general, stop using stylesheets.)
Upvotes: 3