我试图弄清楚如何将TableView与使用qtruby的模型一起使用。我尝试在给出的教程中修改C ++中的示例 http://doc.qt.io/qt-5/modelview.html并提出了如下所示的代码。
问题在于AbstractTableModel的数据方法的实现:只有角色Qt :: DisplayRole按预期工作。角色Qt :: FontRole和Qt :: BackgroundRole不会导致错误,但似乎也没有做任何事情。更糟糕的是,角色Qt :: TextAlignmentRole和Qt :: CheckStateRole如果启用则会导致分段错误。有人能告诉我,如果我在这里做错了吗?
#!/usr/bin/env ruby
require 'Qt'
include Qt
class MyModel < AbstractTableModel
def initialize(p)
super
end
def rowCount(p)
2
end
def columnCount(p)
3
end
def data(index, role)
row = index.row
col = index.column
case role
when Qt::DisplayRole
return Variant.new "Row#{row + 1}, Column#{col + 1}"
when Qt::FontRole
# this doesn't result in an error, but doesn't seem to do anything either
if (row == 0 && col == 0)
boldFont = Font.new
boldFont.setBold(true)
return boldFont
end
when Qt::BackgroundRole
# this doesn't result in an error, but doesn't seem to do anything either
if (row == 1 && col == 2)
redBackground = Brush.new(Qt::red)
return redBackground
end
when Qt::TextAlignmentRole
# # the following causes a segmentation fault if uncommented
# if (row == 1 && col == 1)
# return Qt::AlignRight + Qt::AlignVCenter
# end
when Qt::CheckStateRole
# # the following causes a segmentation fault if uncommented
# if (row == 1 && col == 0)
# return Qt::Checked
# end
end
Variant.new
end
end
app = Application.new ARGV
tableView = TableView.new
myModel = MyModel.new(nil)
tableView.setModel(myModel)
tableView.show
app.exec
答案 0 :(得分:1)
这是因为对于DisplayRole,您正在按预期创建新的Qt :: Variant。
对于其他返回值,您应该使用:
return Qt::Variant.fromValue(boldFont)
return Qt::Variant.fromValue(redBackground)
return Qt::Variant.fromValue(Qt::AlignRight + Qt::AlignVCenter)
return Qt::Variant.fromValue(Qt::Checked)