Skip to content

Instantly share code, notes, and snippets.

@dragonfax
Created November 15, 2016 05:56
Show Gist options
  • Save dragonfax/1fae1ec00691b4731d765969b35833f3 to your computer and use it in GitHub Desktop.
Save dragonfax/1fae1ec00691b4731d765969b35833f3 to your computer and use it in GitHub Desktop.
Example QListView with custom Delegate
package main
import (
"fmt"
"os"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/gui"
"github.com/therecipe/qt/widgets"
)
var htmlDelegate *HTMLDelegate
type HTMLDelegate struct {
widgets.QStyledItemDelegate
}
func InitDelegate(parent core.QObject_ITF) *HTMLDelegate {
item := NewHTMLDelegate(parent)
item.ConnectPaint(paint)
item.ConnectSizeHint(sizeHint)
return item
}
func paint(painter *gui.QPainter, option *widgets.QStyleOptionViewItem, index *core.QModelIndex) {
// We only ever see the last index here. i.e. index 3
fmt.Printf("started painting index %d\n", index.Row())
options := widgets.NewQStyleOptionViewItem2(option)
htmlDelegate.InitStyleOption(options, index)
painter.Save()
doc := gui.NewQTextDocument(nil)
text := options.Text()
doc.SetHtml(text)
options.SetText("")
options.Widget().Style().DrawControl(widgets.QStyle__CE_ItemViewItem, options, painter, nil)
painter.Translate(core.NewQPointF2(options.Rect().TopLeft()))
clip := core.NewQRectF4(0, 0, float64(options.Rect().Width()), float64(options.Rect().Height()))
doc.DrawContents(painter, clip)
painter.Restore()
}
func sizeHint(option *widgets.QStyleOptionViewItem, index *core.QModelIndex) *core.QSize {
options := widgets.NewQStyleOptionViewItem2(option)
htmlDelegate.InitStyleOption(options, index)
var doc gui.QTextDocument
doc.SetHtml(options.Text())
doc.SetTextWidth(float64(options.Rect().Width()))
w := int(doc.IdealWidth())
h := int(doc.Size().Height())
return core.NewQSize2(w, h)
}
func main() {
widgets.NewQApplication(len(os.Args), os.Args)
list := widgets.NewQListView(nil)
listModel := core.NewQStringListModel2([]string{"test 1", "test 2", "test 3", "test 4"}, nil)
list.SetModel(listModel)
htmlDelegate = InitDelegate(list)
list.SetItemDelegate(htmlDelegate) // This line shows only last item in the list.
// list.SetItemDelegate(widgets.NewQStyledItemDelegate(nil)) // This line works properly. as does providing no Delegate.
var layout = widgets.NewQVBoxLayout()
layout.AddWidget(list, 0, core.Qt__AlignCenter)
var window = widgets.NewQMainWindow(nil, 0)
window.SetWindowTitle("Hello World Example")
window.SetMinimumSize2(600, 600)
window.Layout().DestroyQObject()
window.SetLayout(layout)
window.Show()
widgets.QApplication_Exec()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment