现在的位置: 首页 > 综合 > 正文

disable QComboBox中的item及修改其颜色

2018年03月30日 ⁄ 综合 ⁄ 共 1601字 ⁄ 字号 评论关闭

  今天有需要用到disable QComboBox中某些item,本以为这些应该有直接调用的简单方法,结果找了好久都没有找到,只好求助bing,最终得以解决。

  代码如下:

class CComboxOperator : public QComboBox
{
public:
	CComboxOperator(QComboBox *parent = 0);
	~CComboxOperator();
};

CComboxOperator::CComboxOperator(QComboBox *parent) : QComboBox(parent)
{
	QStringList qlstrOperator;
	qlstrOperator << QString(" ") << QString("==") << QString("!=") << QString(">") << QString(">=") << QString("<=") << QString("<");

	addItems(qlstrOperator);
	setItemData(3, 0, Qt::UserRole - 1);  // disable item 3
	setItemData(1, Qt::red, Qt::TextColorRole); // set item 1 "==" red
	setItemData(2, Qt::yellow, Qt::BackgroundColorRole); // set item 2 background yellow
	setItemData(3, Qt::lightGray, Qt::BackgroundColorRole);
}

效果图:


图中“>”不能选中。

void setItemData(int index, const QVariant &value, int role = Qt::UserRole);

        ......
        WhatsThisPropertyRole = 31,
        // Reserved
        UserRole = 32

setItemData(itemIndex, false, Qt:UserRole - 1)这句disable itemIndex,依然没搞懂,有空来查查。

  ......

  搜索到的资料:

    void QStandardItem::setFlags(Qt::ItemFlags flags)
    {
        setData((int)flags, Qt::UserRole - 1);
    }

   Qt Assistant对它的解释:

 void QStandardItem::setFlags ( Qt::ItemFlags flags )

  Sets the item flags for the item to flags.

  The item flags determine how the user can interact with the item. This is often used to disable an item.

enum Qt::ItemFlag
flags Qt::ItemFlags

Constant Value Description
Qt::NoItemFlags 0 It does not have any properties set.
Qt::ItemIsSelectable 1 It can be selected.
Qt::ItemIsEditable 2 It can be edited.
Qt::ItemIsDragEnabled 4 It can be dragged.
Qt::ItemIsDropEnabled 8 It can be used as a drop target.
Qt::ItemIsUserCheckable 16 It can be checked or unchecked by the user.
Qt::ItemIsEnabled 32 The user can interact with the item.
Qt::ItemIsTristate 64 The item is checkable with three separate states.

  对应“Qt::NoItemFlags”。

抱歉!评论已关闭.