There is probably a more direct method, but you can drill down through the layer's renderer to get the categories of a categorised symbology, and subsequently the colours used in their symbol layers.
The categories I used are strings of random integers between 100
and 500
.
For each category, you can get the attribute value used to symbolise it with its .value()
method.
## get the layer
lyr = iface.activeLayer()
## get the field index of the attribute used to classify the symbology
category_field = lyr.fields().indexFromName('category')
## get the layer's renderer
rnd = lyr.renderer()
## get the categories from the categorized renderer
cats = rnd.categories()
## get the dataProvider of the layer to add a new field in which to store the values
prov = lyr.dataProvider()
## name of field
rgb_field_name = 'RGB'
## if field does not exist, create it
if rgb_field_name not in lyr.fields().names():
prov.addAttributes([QgsField(rgb_field_name, QVariant.String)])
lyr.updateFields()
lyr.commitChanges()
## get the layer's features as an iterator
feats = lyr.getFeatures()
## open an edit session
lyr.startEditing()
## iterate through features
for f in feats:
## iterate through the categories for each feature
for c in cats:
## get the attribute value used for the current category
cat_value = c.value()
## check if the current feature's category attribute matches the category value;
## if so, get the fill colour from the feature's symbol
if f[category_field] == cat_value:
## get symbol
s = c.symbol()
## get symbol layers
sym_lyrs = s.symbolLayers()
## get the first symbol layer
sym = sym_lyrs[0]
## get fill colour of symbol layer
col = sym.fillColor()
## get the rgb values of the color
rgb = col.getRgb()
## rgb is a tuple, so convert it to a string and assign it to the new field
f[rgb_field_name] = str(rgb)
## update the feature's attributes
lyr.updateFeature(f)
## save the edits and close the edit session
lyr.commitChanges()
I am not sure how to get the hex color code, but there is probably a way of translating the RGB to hex if you particularly need hex.

@symbol_color
works for labeling, but not in the field calculator.