LoginSignup
1
0

More than 1 year has passed since last update.

QPushButton の配色をsetStyleSheetを使わず変更する

Posted at

はじめに

QWidget の配色を変更する場合...特にQPushButtonの配色を変更したい場合 色々やったが駄目
Qtアプリをダークモードで表示する方法を ChatGPT に聞いた結果 QPushButton の色も変えられるようになった!
これも Qt使いには当たり前過ぎなのかな? 拾えなかったので共有

対象のstyleを変更

QtのQWidgetとそれの派生クラスには元々styleが設定されている
Win10ではwindowsvistaが設定されていて このstyleが色の変更を許可してない模様
なのでfusionwindowsに変更すれば 任意の色を設定可能
ただしwindwosだとかなり古臭いデザインになってしまうのでfusionの方が適切かも
以下のプログラムでは QTextEdit と QPushButton の色を変更

main.cpp
#include <QtWidgets>

int main(int argc, char *argv[]) {
	QApplication app(argc, argv);
	try {
		QWidget w;
		QLayout *l = new QVBoxLayout(&w);
		QTextEdit *te = new QTextEdit(&w);
		QPushButton *pb = new QPushButton("push me", &w);
		QStyle *style = QStyleFactory::create("Fusion");

        w.setWindowTitle("foo");
		qDebug() << "styles:" << QStyleFactory::keys() << "fustion:" << style << "origin:" << pb->style();
		w.setLayout(l);
		l->addWidget(te);
		l->addWidget(pb);
		pb->setStyle(style); // これが肝らしい
		//te->setStyle(style); // QTextEdit は style を変更しなくても変色可能
		te->setProperty("idx", 0);
		te->setPlainText("piyopiyo\npicopico\npukapuka");
		w.connect(pb, &QPushButton::clicked, &w, [&]() {
			int idx = te->property("idx").toInt();
			QPalette p = te->palette();

			if (idx >= 3) {
				idx = 0;
			}
			switch (idx) {
			case 0:
				p.setColor(p.Text, Qt::blue);
				p.setColor(p.Window, Qt::red);
				p.setColor(p.Base, Qt::red);
				p.setColor(p.Button, Qt::red);
				p.setColor(p.ButtonText, Qt::white);
				break;
			case 1:
				p.setColor(p.Text, Qt::yellow);
				p.setColor(p.Window, Qt::green);
				p.setColor(p.Base, Qt::green);
				p.setColor(p.Button, Qt::green);
				p.setColor(p.ButtonText, Qt::yellow);
				break;
			case 2:
				p.setColor(p.Text, Qt::white);
				p.setColor(p.Window, Qt::blue);
				p.setColor(p.Base, Qt::blue);
				p.setColor(p.Button, Qt::blue);
				p.setColor(p.ButtonText, Qt::white);
				break;
			}
			te->setPalette(p);
			pb->setPalette(p);
			idx++;
			te->setProperty("idx", idx);
		});
		w.show();
		return app.exec();
	}
	catch (...) {
		qCritical() << "error!";
	}
	return -1;
}

「push me」を押下するとこんな感じで配色が変わる
image.png image.png image.png image.png

コンソールへの出力情報は次の通り

console
styles: QList("windowsvista", "Windows", "Fusion") fustion: QFusionStyle(0x2603576d400, name = "fusion") origin: QWindowsVistaStyle(0x2603575cbb0, name = "windowsvista")

おわりに

長年のモヤモヤが漸く解消!
確認したのはWindows版の Qt5.15.2, Qt6.2.4, Qt6.5.0
QApplicationへスタイルを設定でもOK
Qt6.5.0 では QApplicationへ"fusion"を設定するとダークモードで表示してくれる

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0