我正在为一个基本的样式表问题而苦苦挣扎。 我正在尝试将样式表应用于主窗口中的 QFrame,但由于某种原因,样式表被忽略了。 这似乎与自定义小部件的Qt样式表和样式表的启用自己的小部件有关,但是我尝试添加paintEvent,但没有帮助。 它一定是简单的东西,但我看不到它。 谁能帮忙?
主.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();
}
主窗口.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
主窗口.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);
}
我终于想通了。 它缺少一个分号。
"padding: 2px"
应该说:
"padding: 2px;"
叹息。