Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

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

In a QTableModel when I enter the following:

print model.supportedDropActions()

I just get:

<PyQt4.QtCore.DropActions object at 0x00000000081172E8>

How can I access an actual list of the supported drop actions from this object? At the documentation, it says, "The DropActions type is a typedef for QFlags. It stores an OR combination of DropAction values."

Note I am doing this in Python (PySide).

Related posts:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Background

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...