如何在 Qt/C++ 中从 QApplication 继承样式表
How to inherite stylesheet from QApplication in Qt/C++
我正在通过阅读如下的 qss 文件来使用外部和通用样式表
QFile File("../Stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
pApp->setStyleSheet(StyleSheet);
stylesheet.qss 很好用
问题
我有一个没有父级初始化的小部件。喜欢
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
: QWidget()
{}
因为此样式表不适用于 WorkspaceWindow 及其子窗口小部件。
我的方法
我创建了一个虚拟 class 继承自 QWidget 并在构造函数中在此 class 上设置样式表。
class PrimaryWidget:public QWidget;
PrimaryWidget::PrimaryWidget()
{
QFile File("../Stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
setStyleSheet(StyleSheet);
}
static PrimaryWidget& get()
{
static PrimaryWidget obj;
return obj;
}
现在我将 WorkspaceWindow 用作
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
: QWidget(&PrimaryWidget::get())
{}
现在工作正常。
问题
如何才能避免这种情况?我可以使用 QApplication 对象为孤立对象(如 WorkspaceWindow)初始化样式表吗?或使 WorkspaceWindow 成为 QApplication 的子对象(某种)?
为了设置样式的灵魂目的而使用虚拟小部件作为父部件sheet感觉不对。
我会将您的代码更改为:
namespace myApp
{
QString styleSheet()
{
QFile file("../Stylesheet.qss");
file.open(QFile::ReadOnly);
const QString styleSheet = QLatin1String(File.readAll());
return styleSheet;
}
}
并且在您的小部件的构造函数中只需:
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow, QWidget *parent)
: QWidget(parent)
{
if (parent == Q_NULLPTR) {
setStyleSheet(myApp::styleSheet());
}
}
我正在通过阅读如下的 qss 文件来使用外部和通用样式表
QFile File("../Stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
pApp->setStyleSheet(StyleSheet);
stylesheet.qss 很好用
问题
我有一个没有父级初始化的小部件。喜欢
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
: QWidget()
{}
因为此样式表不适用于 WorkspaceWindow 及其子窗口小部件。
我的方法
我创建了一个虚拟 class 继承自 QWidget 并在构造函数中在此 class 上设置样式表。
class PrimaryWidget:public QWidget;
PrimaryWidget::PrimaryWidget()
{
QFile File("../Stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
setStyleSheet(StyleSheet);
}
static PrimaryWidget& get()
{
static PrimaryWidget obj;
return obj;
}
现在我将 WorkspaceWindow 用作
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
: QWidget(&PrimaryWidget::get())
{}
现在工作正常。
问题
如何才能避免这种情况?我可以使用 QApplication 对象为孤立对象(如 WorkspaceWindow)初始化样式表吗?或使 WorkspaceWindow 成为 QApplication 的子对象(某种)?
为了设置样式的灵魂目的而使用虚拟小部件作为父部件sheet感觉不对。
我会将您的代码更改为:
namespace myApp
{
QString styleSheet()
{
QFile file("../Stylesheet.qss");
file.open(QFile::ReadOnly);
const QString styleSheet = QLatin1String(File.readAll());
return styleSheet;
}
}
并且在您的小部件的构造函数中只需:
WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow, QWidget *parent)
: QWidget(parent)
{
if (parent == Q_NULLPTR) {
setStyleSheet(myApp::styleSheet());
}
}