QCombobox :: setItemData函数的奇怪行为

时间:2014-02-27 09:09:21

标签: qt qcombobox

我正在处理一个来自QComboBox的(公开)派生的简单类,并注意到setItemData函数的奇怪行为:

一个简单的例子:

QFont font;
font.setItalic(true);
setItemData(0, font, Qt::FontRole);

我确信这必须将组合框中第一个元素的字体更改为斜体。但它没有。 当这段代码在这个组合中正常工作时,我更加惊讶:

setEditable(true);  //setting my derived class editable changes the situation
QFont font;
font.setItalic(true);
setItemData(0, font, Qt::FontRole);

此外,如果我运行我的应用程序(使用我的自定义组合框类),从终端f.e.给出样式选项。 -style plastique然后一切正常,无需设置组合框可编辑。

我在文档中找不到任何关于此的内容。 有谁知道这一切的原因是什么?

这是源代码: .h文件:

class ComboBoxWrapper : public QComboBox
{
  Q_OBJECT;

public:
  ComboBoxWrapper(QWidget* parent = 0);

  const QString& getDefaultValue() const;
  void setDefaultValue(const QString& defaultValue);

private:
    QString defaultValue_;

};

这是.cpp:

ComboBoxWrapper::ComboBoxWrapper(QWidget* parent)
  : QComboBox(parent)
{
  setAutoFillBackground(true);
}

const QString& ComboBoxWrapper::getDefaultValue() const
{
  return defaultValue_;
}

void ComboBoxWrapper::setDefaultValue(const QString& defaultValue)
{
  int index = findText(defaultValue);
  if(-1 == index)
  { /// current value is invalid.
    defaultValue_.clear();
    Q_ASSERT(false);
  }    

  defaultValue_ = defaultValue;
  QFont font = QApplication::font();
  font.setItalic(true);

  setEditable(true);  //setItemData doesn't work without this trick
  setItemData(index, font, Qt::FontRole);
  setEditable(false);
}

0 个答案:

没有答案