Utils

Errors

exception QtBaseException(message, displayPopup=False, *args)

Bases: Exception

Custom Exception base class used to handle exception with our on subset of options

showDialog()

Keyboardmouse

ctrlShiftMultiplier(shiftMultiply=5.0, ctrlMultiply=0.2, altMultiply=1.0)

For offset functions multiply (shift) and minimise if (ctrl) is held down If (alt) then call the reset option

Return multiplier:

multiply value, 0.2 if ctrl 5.0 if shift 1.0 if None

Rtype multiplier:

float

Return reset:

Reset becomes True while resetting for alt

Rtype reset:

bool

eventKeySequence(event, includeShiftForSpecialCharacters=False, acceptedShiftCombinations=None)

Returns the QKeySequence from the KeyEvent

Parameters:
  • event (QtGui.QKeyEvent) –

  • includeShiftForSpecialCharacters (bool) – If True then special characters like ! which map to another key i.e. ! maps to shift+1 then only return the sequence “!” not shift+1

  • acceptedShiftCombinations (list[QtCore.Qt.Key]) – A list of keys which are accepted to be returned with the shift modifier.

Returns:

Return type:

QtGui.QKeySequence

Qtmath

normalized(pt)
magnitude(pt)
distance(pt1, pt2)

Stylesheet

class StyleSheet(styleSheet=None)

Bases: object

styleSheetStr = "QToolTip{background - color: rgb(BACK_COLOR_R, BACK_COLOR_G, BACK_COLOR_B);"
                 "color: black;border: blacksolid 1px;margins: 2px;}"
settings = {"BACK_COLOR_R": 251, "BACK_COLOR_G": 15, "BACK_COLOR_B": 10}
sheet = StyleSheet(styleSheetStr)
sheet.format(settings)
print(sheet.data)
# result
# QToolTip {
#     background-color: rgb(251, 15, 10);
#     color: black;
#     border: black solid 1px;
#     margins: 2px;
# }
classmethod fromPath(path, **kwargs)
Parameters:
  • path (str) – The style stylesheet css file

  • kwargs (dict) – The settings to replace in the style sheet

Return type:

StyleSheet

format(settings)

Formats the stylesheet str with the settings

Parameters:

settings (dict) – A dict containing the str to replace and the value to replace with eg. {“BACK_COLOR_R”: 251}

Returns:

True if successfully formatted

Return type:

bool

valueType(value)

Returns type of value for the stylesheet.pref key value

Parameters:

value

Returns:

stylesheetFromDirectory(directory, name)

Recursively searches directory until the name.css file is found and a Stylesheet instance is returned

Parameters:
  • directory (str) – The absolute path to the directory to search

  • name (str) – the file name to find

Returns:

The style sheet instance or None if no matching file is found

Return type:

tuple(StyleSheet, str)

stylesheetsFromDirectory(directory)

Recursively searches the directory for all .css files and returns StyleSheet instances and file paths

Parameters:

directory (str) – The absolute path to the directory to search

Returns:

Return type:

list(tuple(StyleSheet, str))

loadFonts(fontPaths)

Loads the given ‘.ttf’ font files into the QtGui.QFontDatabase

Parameters:

fontPaths (list(str)) – A list of font files

Returns:

the list of registered font ids from Qt

Return type:

list(str)

unloadFonts()

Unload all loaded zoo fonts

Returns:

loadDefaultFonts()

Loads the zoo core default fonts paths.

Note:

this only needs to be run once per QApplication

Thread

class WorkerSignals(*args: Any, **kwargs: Any)

Bases: QObject

Defines the signals available from a running worker thread.

Supported signals are:

finished

No data

error

tuple (exctype, value, traceback.format_exc() )

result

object data returned from processing, anything

progress

int indicating % progress

error

alias of tuple

result

alias of object

progress

alias of int

class ThreadedFunc(*args: Any, **kwargs: Any)

Bases: QRunnable

Worker thread

Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

Parameters:
  • callback (function) – The function callback to run on this worker thread. Supplied args and kwargs will be passed through to the runner.

  • args – Arguments to pass to the callback function

  • kwargs – Keywords to pass to the callback function

run()

Initialise the runner function with passed args, kwargs.

Uiconstants

Utils

loggingMenu(name=None)
iterParents(widget)

Get all the parents of the widget

Parameters:

widget (Qt.QtWidgets.QWidget.QWidget) – Widget to get the parents of

Returns:

Return type:

list[Qt.QtWidgets.QWidget.QWidget]

iterChildren(widget, skip=None)

Yields all descendant widgets depth-first

Parameters:
  • widget (QtWidgets.QWidget) – Widget to iterate through

  • skip (basestring) – If the widget has this property, it will skip it’s children

Returns:

hasAncestorType(widget, ancestorType, maxIter=20)

Boolean version of ancestor

Parameters:
  • widget (QtWidgets.QWidget) – The target widget to check

  • ancestorType (class) – The type of widget to search for eg. toolsetui.ToolsetsUi

  • maxIter (int) – Max number of iterations to check through the parent and their parents

Returns:

Return type:

invalidateWindow(w)

Invalidate window to force the window to update the sizes. Assumes window to be hidden

Parameters:

w

Returns:

widgetVisible(widget)

Checks if the widget is actually visible. widget.isVisible() only checks if the visible flag is off or on. Even if the parent is invisible and widget is visible, this should still work correctly.

Parameters:

widget – QtWidgets.QWidget

Returns:

updateWidgetSizes(w)

Update the widget sizes, especially useful for resizing and showing

Parameters:

w

Returns:

ancestor(widget, ancestorType, maxIter=20)

Checks if widget has an ancestor of a certain type

Example:

class Ancestor(QtWidgets.QWidget):
    pass

ancestor = Ancestor()
x = QtWidgets.QWidget(ancestor)

hasAncestorType(x, Ancestor) # True
Parameters:
  • widget (QtWidgets.QWidget) – The target widget to check

  • ancestorType (class) – The type of widget to search for eg. toolsetui.ToolsetsUi

  • maxIter (int) – Max number of iterations to check through the parent and their parents

Returns:

Return type:

absQPoint(p)

Get the abs() for qpoint

Parameters:

p (QtCore.QPoint) –

Returns:

Return type:

QtCore.QPoint

safeTreeWidgetIterator(item, flags=PySide2.QtWidgets.QTreeWidgetItemIterator.IteratorFlag.All)

A PyQt and PySide compatible QTreeWidgetItemIterator which handles incrementing the iterator on each loop to avoid the infinite loop.

Parameters:
  • item (QtWidgets.QTreeWidget or QtWidgets.QTreeWidgetItemIterator) –

  • flags (int) – Qt QTreeWidgetItemIterator flags

Returns:

Generator which returns each item in the tree

Return type:

list[QtWidgets.QtTreeWidgetItem]

getWidgetTree(widget, maxIter=20)

Get the widget’s tree from its ancestors

Parameters:

widget

Returns:

isNameInChildren(widgetName, parentWidget)
hsvColor(hue, sat=1.0, val=1.0, alpha=1.0)

Create a QColor from the hsvaValues

Note

All the values must be in the range 0.0-1.0.

Parameters:
  • hue (float) – The hue value

  • sat (float) – The saturation value.

  • val (float) – The value.

  • alpha (float) – The alpha component of the HSV color.

Return type:

QtGui.QColor

colorStr(c)

Generate a hex string code from a QColor

hBoxLayout(parent=None, margins=(2, 2, 2, 2), spacing=2)
hframeLayout(parent=None)
vframeLayout(parent=None)
vBoxLayout(parent=None, margins=(2, 2, 2, 2), spacing=2)
hlineEdit(labelName, parent, enabled=True)
vlineEdit(labelName, parent, enabled=True)
recursivelySetActionVisiblity(menu, state)

Will recursively set the visible state of the QMenu actions

Parameters:

menu (QMenu) – The QMenu to search

desktopPixmapFromRect(rect)

Generates a pixmap on the specified QRectangle.

Parameters:

rect (QRect) – Rectangle to Snap

Returns:

Captured pixmap

Return type:

QPixmap

windowOffset(window)

Gets the window offset often not seen in frameless windows.

Parameters:

window (QtWidgets.QMainWindow) – the Window widget

Returns:

The offset

Return type:

QtCore.QPoint

widgetCenter(widget)

Widget Center

Parameters:

widget (QtWidgets.QWidget) – Widget to the center of

Return type:

QtCore.QPoint

Returns:

Center point of widget

updateStyle(widget)

Updates a widget after a style object name change. eg. widget.setObjectName()

Parameters:

widget

Returns:

squaredLength(pt)

Squared length of a point. Higher performance than length, at the cost of accuracy.

Parameters:

pt (Qt.QtCore.QPoint) –

Returns:

Return type:

int

setStylesheetObjectName(widget, name, update=True)

Sets the widget to have the object name as set in the stylesheet

#redselection {
    background-color: red;
}
btn = QtWidgets.QPushButton("Hello World")
utils.setStylesheetObjectName(btn, "redselection")
Parameters:
  • widget – Widget to apply object name to

  • name – The object name in stylesheet without the ‘#’

Returns:

widgetsAt(pos)

Get widgets underneath

Parameters:

pos (QtCore.QPoint) –

Returns:

Returns list of all widgets underneath pos

Return type:

List[Tuple[QWidget], QPoint]]

widgetsUnderCursor()

Gets the widgets underneath the cursor

Returns:

Return type:

List[Tuple[QWidget, QPoint]]

clickUnder(pos, under=1, button=PySide2.QtCore.Qt.MouseButton.LeftButton, modifier=PySide2.QtCore.Qt.KeyboardModifier.NoModifier)

Clicks under the widget

Parameters:
  • pos (QtCore.QPoint) –

  • under (int) – Number of iterations under

Returns:

widgetAttributesString(widget, trueOnly=True)
Parameters:

widget (QtWidgets.QWidget) –

Returns:

Return type:

windowFlagsString(windowFlags)

Returns a nice string that describes what’s inside a windowFlags object

print(windowFlagsString(self.windowFlags()))

Prints out:

QtCore.Qt.Dialog
    | QtCore.Qt.WindowTitleHint
    | QtCore.Qt.WindowSystemMenuHint
    | QtCore.Qt.WindowCloseButtonHint
    | QtCore.Qt.WindowContextHelpButtonHint
Parameters:

windowFlags

Returns:

keyboardModifiers()

Keyboard modifiers

Returns:

Return type:

Qt.QtCore.Qt.KeyboardModifier

flagTypes(flag)

Extracts the flag states as strings eg:

flagTypes(QtWidgets.QStyle.StateFlag)

[QtWidgets.QStyle.StateFlag.State_HasFocus, QtWidgets.QStyle.StateFlag.State_AutoRaise, QtWidgets.QStyle.StateFlag.State_Bottom, QtWidgets.QStyle.StateFlag.State_Children, etc]

Parameters:

flag

Returns:

flagString(value, flag, fullPath=False)

Returns a string with all the flags associated with the value, based on flag

eg. flags = flagString(option.state, QtWidgets.QStyle.StateFlag) # flags: [“QtWidgets.QStyle.StateFlag.State_On”, “QtWidgets.QStyle.StateFlag.State_HasFocus”

If fullPath is false, it will just return the last part of the flag name:

# flags: [“State_On”, “State_HasFocus”]

Parameters:
  • value

  • flag

  • fullPath – Return the last state instead eg [“State_On”, State_HasFocus]

Returns:

alignmentString(alignmentFlags)

Returns a nice string that describes what’s inside a alignment object

Parameters:

alignmentFlags – Alignment flags

Returns:

dpiMult()
dpiScale(value)

Resize by value based on current DPI

Parameters:

value (int) – the default 2k size in pixels

Return value:

the size in pixels now dpi monitor ready (4k 2k etc)

Rtype value:

int

dpiScaleDivide(value)

Inverse resize by value based on current DPI, for values that may get resized twice

Parameters:

value (int) – the size in pixels

Return value:

the divided size in pixels

Rtype value:

int

pixmapFromIcon(image)

Returns the first available size for a QImage

Parameters:

image (QtGui.QIcon) –

Returns:

marginsDpiScale(left, top, right, bottom)

Convenience function to return contents margins

Parameters:
  • left

  • top

  • right

  • bottom

Returns:

pointByDpi(point)

Scales the QPoint by the current dpi scaling from maya.

Parameters:

point (QtCore.QPoint) – The QPoint to Scale by the current dpi settings

Returns:

The newly scaled QPoint

Return type:

QtCore.QPoint

sizeByDpi(size)

Scales the QSize by the current dpi scaling from maya.

Parameters:

size (QSize) – The QSize to Scale by the current dpi settings

Returns:

The newly scaled QSize

Return type:

QSize

clearLayout(layout)

Clear the elements of a layout

Parameters:

layout (QtWidgets.QLayout) – The QT Layout instance.

layoutItems(layout)

Retrieves the items from the layout and returns it as a list

Parameters:

layout – The layout to retrieve the items from

Returns:

List of items from layout

Return type:

list of QtWidgets.QLayoutItem

layoutItem(widget)

Get the widgets layout item

Parameters:

widget (QWidget) – The Widget instance.

Returns:

Return type:

QtWidgets.QWidget

layoutIndex(widget)

Get the layout index of the widget in its layout

Parameters:

widget

Returns:

Return type:

int

layoutWidgets(layout)

Retrieves the widgets from the layout and returns it as a list

Parameters:

layout – The layout to retrieve the widgets from

Returns:

List of widgets from layout

Return type:

list

screensContainPoint(point)

Checks if point is within the screens

Parameters:

point

Returns:

currentScreenGeometry()

Gets the current screen geometry.

Return type:

QtCore.QRect

currentScreen()

Gets current screen.

Return type:

QRect

containWidgetInScreen(widget, pos=None)

Forces the provided widget to be within the screen and returns the resulting position

Parameters:

widget (QtWidgets.QWidget) – The Widget to change.

Return type:

QtCore.QPoint

resetFixedHeight(widget, policy=PySide2.QtWidgets.QSizePolicy.Policy.Preferred)

Reset the fixed width

:param widget:The widget to affect :type widget: QtWidgets.QWidget :param policy: Policy to change back to (from Fixed) :type policy: QtWidgets.QSizePolicy

resetFixedWidth(widget, policy=PySide2.QtWidgets.QSizePolicy.Policy.Preferred)

Reset the fixed width

Parameters:
  • widget (QtWidgets.QWidget) – The widget to affect

  • policy (QtWidgets.QSizePolicy) – Policy to change back to (from Fixed)

resetFixedSize(widget, policy=<PySide2.QtWidgets.QSizePolicy(horizontalPolicy = QSizePolicy::Preferred, verticalPolicy = QSizePolicy::Preferred)>)

Reset the fixed size

Parameters:
  • widget (QtWidgets.QWidget) – The widget to affect

  • policy (QtWidgets.QSizePolicy) – Policy to change back to (from Fixed)

singleShotTimer(func, time=0)

Shorthand for QtCore.QTimer.singleShot()

Parameters:
  • time (int) – Time in milliseconds to run the function

  • func (callable) – Function to pass through to the single shot timer

setCursor(cursor)

Set cursor

Parameters:

cursor – Cursor

Type:

QtCore.Qt.CursorShape

Returns:

restoreCursor()

Resets the cursor back to default

Returns:

setVSizePolicy(widget, p)

Less painful way of setting the size policies of widgets

Parameters:

p (QtWidgets.QSizePolicy) – The new size policy to put into the vertical policy

Returns:

Return type:

setHSizePolicy(widget, p)

Less painful way of setting the size policies of widgets

Parameters:

p (QtWidgets.QSizePolicy) – The new size policy to put into the horizontal policy

Returns:

Return type:

setSizeHint(widget, size)

Possibly hacky approach to set the size hint. Monkey-patch

Parameters:
  • widget (QtWidgets.QWidget) –

  • size (QtCore.QSize) –

Returns:

Return type:

mainWindow()

Returns the main window depending on program

Returns:

Return type:

QtWidgets.QWidget

processUIEvents()

Shorthand for QtWidgets.QApplication.processEvents()

forceWindowUpdate(w)

Forces a window update. Fairly hacky so use when everything else fails

Parameters:

w (QtWidgets.QMainWindow) – The window to force

firstVisibleChild(w)

Get first visible child

Parameters:

w (QtWidgets.QWidget) – Widget

Returns:

Return type:

QtWidgets.QWidget

clearFocusWidgets()

Clear focus if it has the “clearFocus” property set by the developer

setForcedClearFocus(w, active=True)

Set widget to have forced clearFocus. Some widgets need this

Parameters:
  • active

  • w (QtWidgets.QWidget) –

qTreeViewRemoveDottedLines(tree)

Removes the dotted lines on selection for tree widget

https://stackoverflow.com/questions/15830383/get-rid-of-qts-dotted-outline-on-qlistview-items

Parameters:

tree (QtWidgets.QTreeWidget) –

setShadowEffectEnabled(widget, enabled)

Set shadow effect for a widget

Parameters:
  • widget (QtWidgets.QWidget) –

  • enabled

blockSignalsContext(qtObjects)

Context Manager(with) statement which temporarily disables signals for the provided QObjects.

Parameters:

qtObjects (QtCore.QObject) – Iterable of QObjects which will have their signals temporarily blocked.

wid = QtWidgets.QtWidget()
with blockSignalsContext((wid,)):
    # do something

Validators

class UpperCaseValidator(*args: Any, **kwargs: Any)

Bases: QValidator

Validator that keeps the text upper case todo: untested

validate(string, pos)