![](/img/trans.png)
[英]Using PyQt4 - QTableView with SQLAlchemy using QSqlTableModel (or not)
[英]using delegate for image in qtableview pyqt4 python?
此代碼將僅在同一行中顯示同一圖像。 如何在ImageDelegate中傳遞圖像的不同路徑? 謝謝
class testQT4(QtGui.QTableView):
def __init__(self, parent=None):
QtGui.QTableView.__init__(self, parent)
self.setItemDelegateForColumn(1, ImageDelegate(parent))
#table header
header = [ 'ID','image']
tabledata = [[1,2],[3,4]]
#create table model
self.model = MyTableModel(tabledata, header, self)
#set table model
self.setModel(self.model)
class ImageDelegate(QtGui.QStyledItemDelegate):
def __init__(self, parent):
print dir(self)
QtGui.QStyledItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
painter.fillRect(option.rect, QtGui.QColor(191,222,185))
# path = "path\to\my\image.jpg"
self.path = "image.bmp"
image = QtGui.QImage(str(self.path))
pixmap = QtGui.QPixmap.fromImage(image)
pixmap.scaled(50, 40, QtCore.Qt.KeepAspectRatio)
painter.drawPixmap(option.rect, pixmap)
在委托的paint方法中,您可以通過index.model()
訪問模型。 然后,您可以在模型中查詢要顯示的數據(圖像)。 例如,通過將Qt.UserRole用於模型的data
功能。
另一個可能甚至更容易的解決方案是,模型的數據函數可以為Qt.DecorationRole返回QIcon,QPixmap,QImage和QColor之一。 在這種情況下,無需委托。
例如,以下代碼將把Icon放在表的(僅)字段中:
from PyQt4 import QtGui, QtCore
import PyQt4.uic
# using QtDesigner to just put a TableView in a Widget
Form, Base = PyQt4.uic.loadUiType(r'TableView.ui')
class TableModel( QtCore.QAbstractTableModel ):
def __init__(self, parent=None):
super(TableModel,self).__init__(parent)
def rowCount(self, parent=QtCore.QModelIndex()):
return 1
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def data(self, index, role):
if index.isValid():
if role==QtCore.Qt.DecorationRole:
return QtGui.QIcon("ChipScope.png")
return None
class TableViewUi(Form, Base ):
def __init__(self, parent=None):
Form.__init__(self)
Base.__init__(self,parent)
def setupUi(self, parent):
Form.setupUi(self,parent)
model = TableModel()
self.tableView.setModel(model)
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = TableViewUi()
ui.setupUi(ui)
MainWindow.setCentralWidget(ui)
MainWindow.show()
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.