我试图使用样式表中的Q_PROPERTY集来更改QPalette中的值,这可能吗?例如,如果我在我的QStyle小部件中将MainWindow设置为Fusion,是否可以使用此方法更改Qt::Window等?
一切都编译好了,但是唯一显示的颜色是黑色,所以变量可能被一个垃圾值填充了吗?据我所知,样式表覆盖了所有其他内容,因此,据猜测,样式表没有及时加载到构造函数中?
mainwindow.cpp
#include <QStyleFactory>
#include <QWidget>
#include <QFile>
#include "theme.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
{
QFile File("://stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
qApp->setStyleSheet(StyleSheet);
Theme *themeInstance = new Theme;
QApplication::setStyle(QStyleFactory::create("Fusion"));
QPalette dp;
dp.setColor(QPalette::Window, QColor(themeInstance->customColor()));
qApp->setPalette(dp);
}theme.h
#ifndef THEME_H
#define THEME_H
class Theme : public QWidget
{
Q_OBJECT
Q_PROPERTY(QColor customColor READ customColor WRITE setCustomColor DESIGNABLE true)
public:
Theme(QWidget *parent = nullptr);
QColor customColor() const { return m_customColor; }
void setCustomColor(const QColor &c) { m_customColor = c; }
private:
QColor m_customColor;
};
#endif // THEME_Hstylesheet.qss
* { // global only for test purposes
qproperty-customColor: red;
}发布于 2018-04-23 17:01:16
QSS不是自动调用的,它们通常是在显示小部件时更新的,在您的示例中,由于没有显示themeInstance,所以不使用样式表。可以使用polish()的QStyle方法强制绘画
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr):QMainWindow{parent}{
qApp->setStyleSheet("Theme{qproperty-customColor: red;}");
Theme *themeInstance = new Theme;
qApp->setStyle(QStyleFactory::create("Fusion"));
qApp->style()->polish(themeInstance);
QPalette dp;
dp.setColor(QPalette::Window, QColor(themeInstance->customColor()));
qApp->setPalette(dp);
}
};https://stackoverflow.com/questions/49982210
复制相似问题