Access values of dropActions in model (PySide/PyQt/Qt)

后端 未结 1 719
孤独总比滥情好
孤独总比滥情好 2020-12-21 10:00

In a QTableModel when I enter the following:

print model.supportedDropActions()

I just get:



        
相关标签:
1条回答
  • 2020-12-21 10:30

    Background

    First, make sure you understand how the bitwise-encoding works for these flags. There are really good descriptions in the accepted answers here:

    • What are bitwise operators?
    • How to find specific Qt.ItemFlag occurrence into custom Qt.ItemFlags instance in PyQt?

    Everyone that uses Qt and its relatives should read them, they will save a lot of headache if you ever want to extract information from the bitwise-encoded values.

    Solution

    While the following isn't for drop actions, but for item data roles, the principles are the exact same. As mentioned in the comments on the original post, you can recast the encoded value as an int and then decode it to a human-readable format using the enumeration (i.e., the translation between integer and role) provided by Qt online. I don't know why sometimes the docs represent the integers as hex versus decimals.

    In what follows, I represented the enumeration that I found online in a dictionary with the int as key, and the human-readable string description as value. Then use a function that casts the role as an int to do the translation, using that dictionary.

    #Create a dictionary of all data roles
    dataRoles = {0: 'DisplayRole', 1: 'DecorationRole', 2: 'EditRole', 3: 'ToolTipRole',\
                4: 'StatusTipRole', 5: 'WhatsThisRole', 6: 'FontRole', 7: 'TextAlignmentRole',\
                8: 'BackgroundRole', 9: 'ForegroundRole', 10: 'CheckStateRole', 13: 'SizeHintRole',\
                14: 'InitialSortOrderRole', 32: 'UserRole'} 
    
    #Return role in a human-readable format
    def roleToString(flagDict, role):
        recastRole = int(role)  #recast role as int
        roleDescription = flagDict[recastRole]
        return roleDescription
    

    Then to use it, for instance in a model where roles are being thrown around and I want to see what's doing:

    print "Current data role: ", roleToString(dataRoles, role)
    

    There are different ways to do it, but I find this very intuitive and easy to use.

    0 讨论(0)
提交回复
热议问题