2009-05-06 45 views
2

我在繼承QAbstractItemDelegate。這是我的代碼。建議,歡迎:神祕:在Qt中,爲什麼會調用editorEvent,但不是createEditor?

QWidget *ParmDelegate::createWidget(Parm *p, const QModelIndex &index) const { 
    QWidget *w; 
    if (index.column() == 0) { 
     w = new QLabel(p->getName().c_str()); 
    } else { 
     if (p->isSection()) 
      return NULL; 
     w = p->createControl(); 
    } 
    return w; 
} 

QWidget *ParmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { 
    cout << "createEditor called" << endl; 
    Parm *p = reinterpret_cast<Parm*>(index.internalPointer()); 
    QWidget *retval = createWidget(p, index); 
    retval->setFocusPolicy(Qt::StrongFocus); 
    retval->setParent(parent); 
    return retval; 
} 

void ParmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { 
    QRect rect(option.rect); 
    editor->setGeometry(QRect(QPoint(0,0), rect.size())); 
} 

void ParmDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { 
    Parm *p = reinterpret_cast<Parm*>(index.internalPointer()); 
    scoped_ptr<QWidget> w(createWidget(p, index)); 
    if (!w) 
     return; 
    QRect rect(option.rect); 
    w->setGeometry(QRect(QPoint(0,0), rect.size())); 
    w->render(painter, rect.topLeft()); 
} 

QSize ParmDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { 
    Parm *p = reinterpret_cast<Parm*>(index.internalPointer()); 
    scoped_ptr<QWidget> w(createWidget(p, index)); 
    if (!w) 
     return QSize(0,0); 
    return w->sizeHint(); 
} 

bool ParmDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index) { 
    cout << "editorEvent called" << endl; 
    return false; 
} 

當這樣跑,我只能看到editorEvent獲取每個編輯的事件稱爲兩次 - 沒有createEditor!

+0

嘗試雙擊您想要編輯的項目。它看起來像雙擊觸發另一個編輯事件。 – 2009-05-06 10:06:49

回答

7

從Qt的AbstractItemDelegate文檔:

要提供自定義編輯,也有可以使用的兩種方法。第一種方法是創建一個編輯器小部件,並將其直接顯示在該項目的頂部。爲此,您必須重新實現createEditor()以提供編輯器小部件,setEditorData()以使用模型中的數據填充編輯器,以及setModelData(),以便代表可以使用編輯器中的數據更新模型。

第二種方法是通過重新實現editorEvent()直接處理用戶事件。

這似乎表明您錯過了某些東西來觸發第一種方法。我的猜測是,您的型號的data()函數沒有返回Qt::EditRole選項的適當值。

+1

你讓我知道了,謝謝!我沒有在模型的標誌中設置Qt :: ItemIsEditable。 – 2009-05-06 17:57:56

0

我已經實現了一個我從QItemDelegate中接受過的TableView。然後我有類似的問題。我追蹤到不調用'return QItemDelegate :: editorEvent(event,model,option,index);'在editorEvent(...)方法中。

你可以試試這個。也許它有幫助。

+0

感謝您的回覆。不幸的是,它沒有幫助。 僅供參考,我是繼承QAbstractItemDelegate,而不是QItemDelegate ... – 2009-05-06 17:10:08

相關問題