如何为QTableView表头中的右键点击获取上下文菜单?

8 浏览
0 Comments

如何为QTableView表头中的右键点击获取上下文菜单?

下面的示例代码(受到这里的影响)具有右键上下文菜单,当用户点击表格中的单元格时会显示。是否可能在表头右键单击时有不同的右键上下文菜单?如果可以,我该如何修改代码以实现这一点?

import re
import operator
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())
class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.tabledata = [('apple', 'red', 'small'),
                          ('apple', 'red', 'medium'),
                          ('apple', 'green', 'small'),
                          ('banana', 'yellow', 'large')]
        self.header = ['fruit', 'color', 'size']
        # 创建表格
        self.createTable()
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.tv)
        self.setLayout(layout)
    def popup(self, pos):
        for i in self.tv.selectionModel().selection().indexes():
            print i.row(), i.column()
        menu = QMenu()
        quitAction = menu.addAction("退出")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == quitAction:
            qApp.quit()
    def createTable(self):
        # 创建视图
        self.tv = QTableView()
        self.tv.setStyleSheet("gridline-color: rgb(191, 191, 191)")
        self.tv.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tv.customContextMenuRequested.connect(self.popup)
        # 设置表格模型
        tm = MyTableModel(self.tabledata, self.header, self)
        self.tv.setModel(tm)
        # 设置最小大小
        self.tv.setMinimumSize(400, 300)
        # 隐藏网格线
        self.tv.setShowGrid(True)
        # 设置字体
        font = QFont("Calibri (Body)", 12)
        self.tv.setFont(font)
        # 隐藏垂直表头
        vh = self.tv.verticalHeader()
        vh.setVisible(False)
        # 设置水平表头属性
        hh = self.tv.horizontalHeader()
        hh.setStretchLastSection(True)
        # 设置列宽以适应内容
        self.tv.resizeColumnsToContents()
        # 设置行高
        nrows = len(self.tabledata)
        for row in xrange(nrows):
            self.tv.setRowHeight(row, 18)
        # 启用排序
        self.tv.setSortingEnabled(True)
        return self.tv
class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, headerdata, parent=None, *args):
        """ datain: 一个列表的列表
            headerdata: 一个字符串列表
        """
        QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = datain
        self.headerdata = headerdata
    def rowCount(self, parent):
        return len(self.arraydata)
    def columnCount(self, parent):
        return len(self.arraydata[0])
    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])
    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        return QVariant()
    def sort(self, Ncol, order):
        """按给定的列数对表格进行排序。
        """
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
        if order == Qt.DescendingOrder:
            self.arraydata.reverse()
        self.emit(SIGNAL("layoutChanged()"))
if __name__ == "__main__":
    main()

0