我试图弄清楚如何将 TableView 与使用 qtruby 的模型一起使用。我尝试在 http://doc.qt.io/qt-5/modelview.html给出的教程中调整 C++ 中的示例,并提出了如下所示的代码。
问题在于 AbstractTableModel 的 data 方法的实现:只有角色 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