QStyledItemDelegate我有一個自定義串列,并且在視圖(帶有數量,但在文本編輯中,而不是旋轉框)。
此文本編輯應該能夠與模型進行通信。目前我只能繪制一個空的textEdit,但我不知道如何將它正確連接到editorEvent(和createEditor,setEditorData)。
void CustomDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &opt,
const QModelIndex &idx) const
{
// My other painting stuff (labels, shapes...)
QStyleOptionFrame panelFrame;
QLineEdit lineEdit;
panelFrame.initFrom(&lineEdit);
panelFrame.rect = rectLE;
panelFrame.state |= QStyle::State_Sunken;
QApplication::style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panelFrame, painter);
}
QWidget *CustomDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
auto editor = new QLineEdit(parent);
editor->setText("test");
return editor;
}
void CustomDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
auto lineEdit = dynamic_cast<QLineEdit*>(editor);
if(lineEdit)
{
lineEdit->setText("test2");
}
}
結果我只能看到一個空的lineEdit并且不能真正與之互動。
- 如果我
lineEdit在一個modelIndex代表中有多個 s,我怎么能在setEditorDataand中區分它們createEditor?
謝謝
uj5u.com熱心網友回復:
默認情況下,編輯器QAbstractItemView僅由編輯觸發器創建,這些觸發器已設定為它。參考檔案
要使視圖在渲染行作為常規小部件的意義上具有互動性,您可以使用一種解決方法。
我已經將這種方法與QListViewand一起使用QStyledItemDelegate。
當我遇到同樣的問題時,我跟蹤了 aviewport的滑鼠移動事件,以QModelIndex在滑鼠游標下獲取 a ,如果它有效且與以前的值不同,我關閉一個編輯器(如果打開了一個)并打開一個新的一種使用方法QAbstractItemView::closePersistentEditor和QAbstractItemView::openPersistentEditor。
在我的QStyledItemDelegate派生類中,我重寫了createEditor,setEditorData和updateEditorGeometry方法。
createEditor只需創建一個小部件,在setGeometryupdateEditorGeometry到編輯器中,setEditorData獲取要渲染的所需資料QModelIndex并將其設定到編輯器小部件。
我用來在paint方法視圖中呈現所有行的同一個小部件類。
uj5u.com熱心網友回復:
我在實作中忘記了幾件事:
lineEdit要與標志“互動”,Qt::ItemIsEditable必須在 中設定QAbstractListModel::flags(),否則不會呼叫 Delegate 中的Editor函式。updateEditorGeometry()在您指定lineEdit' 位置的位置重新實作。重新實作
setModelData()可以與模型通信的位置。之后在Delegate的
paint()函式中繪制文本drawPrimitive(drawPrimitive只是繪制框架,但您也想繪制您在lineEdit中撰寫的文本。您可以從模型中獲取)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491178.html
上一篇:帶有專有編解碼器的QtWebengine5.15.10,在Ubuntu22.04上構建問題
下一篇:在PyQTGUI中繪制圖表
