Add a function to convert QColor to CSS rgba format

This commit is contained in:
Veronica Berglyd Olsen
2024-03-27 13:11:37 +01:00
parent 3e66968387
commit 2d9b57b534
6 changed files with 67 additions and 62 deletions
+6 -1
View File
@@ -36,7 +36,7 @@ from configparser import ConfigParser
from urllib.parse import urljoin from urllib.parse import urljoin
from urllib.request import pathname2url from urllib.request import pathname2url
from PyQt5.QtGui import QDesktopServices from PyQt5.QtGui import QColor, QDesktopServices
from PyQt5.QtCore import QCoreApplication, QUrl from PyQt5.QtCore import QCoreApplication, QUrl
from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout
@@ -382,6 +382,11 @@ def numberToRoman(value: int, toLower: bool = False) -> str:
return roman.lower() if toLower else roman return roman.lower() if toLower else roman
def cssCol(col: QColor, alpha: int | None = None) -> str:
"""Convert a QColor object to an rgba entry to use in CSS."""
return f"rgba({col.red()}, {col.green()}, {col.blue()}, {alpha or col.alpha()})"
## ##
# Encoder Functions # Encoder Functions
## ##
+19 -28
View File
@@ -41,6 +41,7 @@ from PyQt5.QtWidgets import (
) )
from novelwriter import CONFIG, SHARED from novelwriter import CONFIG, SHARED
from novelwriter.common import cssCol
from novelwriter.constants import nwHeaders, nwUnicode from novelwriter.constants import nwHeaders, nwUnicode
from novelwriter.core.tohtml import ToHtml from novelwriter.core.tohtml import ToHtml
from novelwriter.enum import nwItemType, nwDocAction, nwDocMode from novelwriter.enum import nwItemType, nwDocAction, nwDocMode
@@ -467,35 +468,25 @@ class GuiDocViewer(QTextBrowser):
"""Generate an appropriate style sheet for the document viewer, """Generate an appropriate style sheet for the document viewer,
based on the current syntax highlighter theme. based on the current syntax highlighter theme.
""" """
colText = SHARED.theme.colText colText = cssCol(SHARED.theme.colText)
colHead = SHARED.theme.colHead colHead = cssCol(SHARED.theme.colHead)
colVals = SHARED.theme.colVal colVals = cssCol(SHARED.theme.colVal)
colMark = SHARED.theme.colMark colMark = cssCol(SHARED.theme.colMark)
colKeys = SHARED.theme.colKey colKeys = cssCol(SHARED.theme.colKey)
colHide = SHARED.theme.colHidden colOpts = cssCol(SHARED.theme.colOpt)
colMods = SHARED.theme.colMod colHide = cssCol(SHARED.theme.colHidden)
colOpts = SHARED.theme.colOpt colMods = cssCol(SHARED.theme.colMod)
styleSheet = ( self.document().setDefaultStyleSheet(
"body {{color: rgb({rT}, {gT}, {bT});}}\n" f"body {{color: {colText};}}\n"
"h1, h2, h3, h4 {{color: rgb({rH}, {gH}, {bH});}}\n" f"h1, h2, h3, h4 {{color: {colHead};}}\n"
"a {{color: rgb({rA}, {gA}, {bA});}}\n" f"a {{color: {colVals};}}\n"
"mark {{background-color: rgba({rE}, {gE}, {bE}, {aE});}}\n" f"mark {{background-color: {colMark};}}\n"
".tags {{color: rgb({rK}, {gK}, {bK});}}\n" f".tags {{color: {colKeys};}}\n"
".optional {{color: rgb({rO}, {gO}, {bO});}}\n" f".optional {{color: {colOpts};}}\n"
".comment {{color: rgb({rC}, {gC}, {bC});}}\n" f".comment {{color: {colHide});}}\n"
".synopsis {{color: rgb({rM}, {gM}, {bM});}}\n" f".synopsis {{color: {colMods};}}\n"
".title {{text-align: center;}}\n" ".title {text-align: center;}\n"
).format(
rT=colText.red(), gT=colText.green(), bT=colText.blue(),
rH=colHead.red(), gH=colHead.green(), bH=colHead.blue(),
rA=colVals.red(), gA=colVals.green(), bA=colVals.blue(),
rE=colMark.red(), gE=colMark.green(), bE=colMark.blue(), aE=colMark.alpha(),
rK=colKeys.red(), gK=colKeys.green(), bK=colKeys.blue(),
rC=colHide.red(), gC=colHide.green(), bC=colHide.blue(),
rM=colMods.red(), gM=colMods.green(), bM=colMods.blue(),
rO=colOpts.red(), gO=colOpts.green(), bO=colOpts.blue(),
) )
self.document().setDefaultStyleSheet(styleSheet)
return return
+1 -1
View File
@@ -565,7 +565,7 @@ class GuiProjectTree(QTreeWidget):
# Auto Scroll # Auto Scroll
self._scrollMargin = SHARED.theme.baseIconSize self._scrollMargin = SHARED.theme.baseIconSize
self._scrollDirection = 0 self._scrollDirection = 0
self._scrollTimer = QTimer() self._scrollTimer = QTimer(self)
self._scrollTimer.timeout.connect(self._doAutoScroll) self._scrollTimer.timeout.connect(self._doAutoScroll)
self._scrollTimer.setInterval(250) self._scrollTimer.setInterval(250)
+13 -13
View File
@@ -38,7 +38,7 @@ from PyQt5.QtGui import (
from novelwriter import CONFIG from novelwriter import CONFIG
from novelwriter.enum import nwItemClass, nwItemLayout, nwItemType from novelwriter.enum import nwItemClass, nwItemLayout, nwItemType
from novelwriter.error import logException from novelwriter.error import logException
from novelwriter.common import NWConfigParser, minmax from novelwriter.common import NWConfigParser, cssCol, minmax
from novelwriter.constants import nwLabels from novelwriter.constants import nwLabels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -440,24 +440,24 @@ class GuiTheme:
# Flat Tab Widget and Tab Bar: # Flat Tab Widget and Tab Bar:
self._styleSheets[STYLES_FLAT_TABS] = ( self._styleSheets[STYLES_FLAT_TABS] = (
"QTabWidget::pane {{border: 0;}} " "QTabWidget::pane {border: 0;} "
"QTabWidget QTabBar::tab {{border: 0; padding: {0}px {1}px;}} " f"QTabWidget QTabBar::tab {{border: 0; padding: {bPx}px {dPx}px;}} "
"QTabWidget QTabBar::tab:selected {{color: rgb({2}, {3}, {4});}} " f"QTabWidget QTabBar::tab:selected {{color: {cssCol(hCol)};}} "
).format(bPx, dPx, hCol.red(), hCol.green(), hCol.blue()) )
# Minimal Tool Button # Minimal Tool Button
self._styleSheets[STYLES_MIN_TOOLBUTTON] = ( self._styleSheets[STYLES_MIN_TOOLBUTTON] = (
"QToolButton {{padding: {0}px; margin: 0; border: none; background: transparent;}} " f"QToolButton {{padding: {aPx}px; margin: 0; border: none; background: transparent;}} "
"QToolButton:hover {{border: none; background: rgba({1}, {2}, {3}, 0.2);}} " f"QToolButton:hover {{border: none; background: {cssCol(tCol, 48)};}} "
"QToolButton::menu-indicator {{image: none;}} " "QToolButton::menu-indicator {image: none;} "
).format(aPx, tCol.red(), tCol.green(), tCol.blue()) )
# Big Tool Button # Big Tool Button
self._styleSheets[STYLES_BIG_TOOLBUTTON] = ( self._styleSheets[STYLES_BIG_TOOLBUTTON] = (
"QToolButton {{padding: {0}px; margin: 0; border: none; background: transparent;}} " f"QToolButton {{padding: {cPx}px; margin: 0; border: none; background: transparent;}} "
"QToolButton:hover {{border: none; background: rgba({1}, {2}, {3}, 0.2);}} " f"QToolButton:hover {{border: none; background: {cssCol(tCol, 48)};}} "
"QToolButton::menu-indicator {{image: none;}} " "QToolButton::menu-indicator {image: none;} "
).format(cPx, tCol.red(), tCol.green(), tCol.blue()) )
return return
+13 -13
View File
@@ -42,7 +42,7 @@ from PyQt5.QtWidgets import (
from novelwriter import CONFIG, SHARED from novelwriter import CONFIG, SHARED
from novelwriter.enum import nwItemClass from novelwriter.enum import nwItemClass
from novelwriter.common import formatInt, makeFileNameSafe from novelwriter.common import cssCol, formatInt, makeFileNameSafe
from novelwriter.constants import nwFiles from novelwriter.constants import nwFiles
from novelwriter.core.coretools import ProjectBuilder from novelwriter.core.coretools import ProjectBuilder
from novelwriter.extensions.configlayout import NWrappedWidgetBox from novelwriter.extensions.configlayout import NWrappedWidgetBox
@@ -52,7 +52,7 @@ from novelwriter.extensions.versioninfo import VersionInfoWidget
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PANEL_ALPHA = 0.7 PANEL_ALPHA = 178
class GuiWelcome(QDialog): class GuiWelcome(QDialog):
@@ -306,12 +306,12 @@ class _OpenProjectPage(QWidget):
self._selectFirstItem() self._selectFirstItem()
baseCol = self.palette().base().color() mPx = CONFIG.pxInt(4)
self.setStyleSheet(( baseCol = cssCol(self.palette().base().color(), PANEL_ALPHA)
"QListView {{border: none; background: rgba({r},{g},{b},{a});}} " self.setStyleSheet(
"QLineEdit {{border: none; background: rgba({r},{g},{b},{a}); padding: {m}px;}} " f"QListView {{border: none; background: {baseCol};}} "
).format(r=baseCol.red(), g=baseCol.green(), b=baseCol.blue(), f"QLineEdit {{border: none; background: {baseCol}; padding: {mPx}px;}} "
a=PANEL_ALPHA, m=CONFIG.pxInt(4))) )
return return
@@ -518,11 +518,11 @@ class _NewProjectPage(QWidget):
# Styles # Styles
# ====== # ======
baseCol = self.palette().base().color() baseCol = cssCol(self.palette().base().color(), PANEL_ALPHA)
self.setStyleSheet(( self.setStyleSheet(
"QScrollArea {{border: none; background: rgba({r},{g},{b},{a});}} " f"QScrollArea {{border: none; background: {baseCol};}} "
"_NewProjectForm {{border: none; background: rgba({r},{g},{b},{a});}} " f"_NewProjectForm {{border: none; background: {baseCol};}} "
).format(r=baseCol.red(), g=baseCol.green(), b=baseCol.blue(), a=PANEL_ALPHA)) )
return return
+15 -6
View File
@@ -29,16 +29,16 @@ from xml.etree import ElementTree as ET
from tools import writeFile from tools import writeFile
from mocked import causeOSError from mocked import causeOSError
from PyQt5.QtGui import QDesktopServices from PyQt5.QtGui import QColor, QDesktopServices
from PyQt5.QtCore import QUrl from PyQt5.QtCore import QUrl
from novelwriter.common import ( from novelwriter.common import (
checkBool, checkFloat, checkInt, checkIntTuple, checkPath, checkString, checkBool, checkFloat, checkInt, checkIntTuple, checkPath, checkString,
checkStringNone, checkUuid, formatFileFilter, formatInt, formatTime, checkStringNone, checkUuid, cssCol, formatFileFilter, formatInt,
formatTimeStamp, formatVersion, fuzzyTime, getFileSize, hexToInt, isHandle, formatTime, formatTimeStamp, formatVersion, fuzzyTime, getFileSize,
isItemClass, isItemLayout, isItemType, isTitleTag, jsonEncode, hexToInt, isHandle, isItemClass, isItemLayout, isItemType, isTitleTag,
makeFileNameSafe, minmax, numberToRoman, NWConfigParser, openExternalPath, jsonEncode, makeFileNameSafe, minmax, numberToRoman, NWConfigParser,
readTextFile, simplified, transferCase, xmlIndent, yesNo openExternalPath, readTextFile, simplified, transferCase, xmlIndent, yesNo
) )
@@ -494,6 +494,15 @@ def testBaseCommon_numberToRoman():
# END Test testBaseCommon_numberToRoman # END Test testBaseCommon_numberToRoman
@pytest.mark.base
def testBaseCommon_cssCol():
"""Test the cssCol function."""
assert cssCol(QColor(0, 0, 0, 0)) == "rgba(0, 0, 0, 0)"
assert cssCol(QColor(10, 20, 30, 40)) == "rgba(10, 20, 30, 40)"
# END Test testBaseCommon_cssCol
@pytest.mark.base @pytest.mark.base
def testBaseCommon_jsonEncode(): def testBaseCommon_jsonEncode():
"""Test the jsonEncode function.""" """Test the jsonEncode function."""