pyqt - 如何在 PyQt 的 QTableView 中按行而不是单个单元格进行选择?

标签 pyqt selection qtableview

在下面的示例代码中(受 here 的影响很大),我希望选择单击单元格的整行而不是单个单元格。如何更改代码以合并它?

import re
import operator
import os
import sys
import sqlite3
import cookies
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)

        # data
        self.tabledata = [('apple', 'red', 'small'),
                          ('apple', 'red', 'medium'),
                          ('apple', 'green', 'small'),
                          ('banana', 'yellow', 'large')]
        self.header = ['fruit', 'color', 'size']

        # create table
        self.createTable()

        # layout
        layout = QVBoxLayout()
        layout.addWidget(self.tv)
        self.setLayout(layout)

    def createTable(self):
        # create the view
        self.tv = QTableView()
        self.tv.setStyleSheet("gridline-color: rgb(191, 191, 191)")

        # set the table model
        tm = MyTableModel(self.tabledata, self.header, self)
        self.tv.setModel(tm)

        # set the minimum size
        self.tv.setMinimumSize(400, 300)

        # hide grid
        self.tv.setShowGrid(True)

        # set the font
        font = QFont("Calibri (Body)", 12)
        self.tv.setFont(font)

        # hide vertical header
        vh = self.tv.verticalHeader()
        vh.setVisible(False)

        # set horizontal header properties
        hh = self.tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        self.tv.resizeColumnsToContents()

        # set row height
        nrows = len(self.tabledata)
        for row in xrange(nrows):
            self.tv.setRowHeight(row, 18)

        # enable sorting
        self.tv.setSortingEnabled(True)

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, headerdata, parent=None, *args):
        """ datain: a list of lists
            headerdata: a list of strings
        """
        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):
        """Sort table by given column number.
        """
        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()

最佳答案

结果证明这比我想象的要容易。只需添加这一行,就可以按行而不是单元格进行选择。

self.tv.setSelectionBehavior(QAbstractItemView.SelectRows)

关于pyqt - 如何在 PyQt 的 QTableView 中按行而不是单个单元格进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782015/

相关文章:

python - PyQt QGraphicsEllipseItem 旋转偏移

java - JEdi​​torPane 矩形(列)选择模式

QTableView + QSqlTableModel - 如何读取所选行的 id

python - 如何在PyQt5中过滤SQLite3表

c++ - QTableView clearSelection 失败,出现 ASSERT : "!isEmpty()" in file/usr/include/qt4/QtCore/qlist. h,第 282 行

python - (Pyqt5 : How to update selection when current item has been set programatically

python - PyQt:Qt.Popup 小部件有时会在不关闭的情况下失去焦点,变得无法关闭

python - 如何获取 QPixmap 或 QImage 像素的 RGB 值 - Qt, PyQt

javascript - 为什么单击 div 时选择会消失?

wpf - TextBox 焦点上的 ListBoxItem 选择