【问题标题】:How to use Filter Option in QTableWidget如何在 QTableWidget 中使用过滤器选项
【发布时间】:2017-06-05 11:44:53
【问题描述】:

我正在使用 QTableWidget 来显示 csv 数据。当我输入关键字时,我希望执行类似于 excel 的过滤操作。它应该影响所有的行和列。

from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtCore import QString

from PyQt4.QtGui import * 
from PyQt4.QtCore import *

import MySQLdb
import os
import time
import sys
import hashlib
import getpass
import webbrowser
import csv

filter_class = uic.loadUiType("filter.ui")[0]

class Filter_window(QtGui.QWidget, filter_class):
    def __init__(self, parent=None, *args, **kwargs):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        #self.selectall.clicked.connect(self.selectall_application)
        #self.filnext.clicked.connect(self.filnext_application)

         self.loadAll()


    def loadAll(self):

        with open("Rts.csv", "rb") as inpfil:

            reader = csv.reader(inpfil, delimiter = ',')
            csheader = reader.next()
            ncol = len(csheader)
            data = list(reader)
            row_count = len(data)

            self.filterall.setRowCount(row_count)
            self.filterall.setColumnCount(ncol)
            self.filterall.setHorizontalHeaderLabels(QString('%s' % ', '.join(map(str, csheader))).split(","))

            for ii in range(0, row_count):
                print data[ii]

                mainins = data[ii]
                print mainins


                for var in range(0,ncol):                                                  
                    print mainins[var], "\n"
                    self.filterall.setItem(ii, var, QTableWidgetItem(mainins[var]))


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    filterwin = Filter_window()
    filterwin.show()
    sys.exit(app.exec_())

filterall 是 QTableWidget 的对象名称

.ui 代码:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>allCases</class>
 <widget class="QWidget" name="allCases">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>597</width>
    <height>466</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>All Cases</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="3" column="0" colspan="4">
    <widget class="Line" name="line">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
    </widget>
   </item>
   <item row="4" column="3">
    <widget class="QPushButton" name="filnext">
     <property name="font">
      <font>
       <pointsize>12</pointsize>
      </font>
     </property>
     <property name="text">
      <string>Next</string>
     </property>
    </widget>
   </item>
   <item row="4" column="2">
    <widget class="QPushButton" name="selectall">
     <property name="font">
      <font>
       <pointsize>12</pointsize>
      </font>
     </property>
     <property name="text">
      <string>Select All</string>
     </property>
    </widget>
   </item>
   <item row="0" column="1">
    <widget class="QLineEdit" name="filterEdit">
     <property name="toolTip">
      <string/>
     </property>
     <property name="statusTip">
      <string/>
     </property>
     <property name="placeholderText">
      <string>Enter keyword to search</string>
     </property>
    </widget>
   </item>
   <item row="0" column="2">
    <spacer name="horizontalSpacer">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>40</width>
       <height>20</height>
      </size>
     </property>
    </spacer>
   </item>
   <item row="1" column="0" colspan="4">
    <widget class="QTableWidget" name="filterall"/>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

【问题讨论】:

  • 能否也给我们看看filter.ui的内容?
  • 您希望过滤器如何工作?
  • @eyllanesc 如果我过滤,它必须影响所有行。类似于excel中的东西。假设有 12 列。如果我点击标题,它必须显示所有可能的文本,选择后,它必须只显示那些。而且,如果有人在搜索栏中输入内容,它必须在 3,4,5,6 列中搜索...
  • 过滤是按列还是所有列?
  • 选项必须用于特定列,并且必须在所有列中更新结果。在第 3 栏中,有一个单词“YES”。当我选择它时,它必须在第 3 列中显示所有包含“YES”的行。所以最终输出将是这样的,如果第 3 列是“YES”,则将显示第 0-12 列的行。第 3 列也必须可以搜索

标签: python pyqt pyqt4 qtableview qtablewidget


【解决方案1】:

通过点击每列的标题进行过滤,它将显示可能的值,并检查它们将过滤。

完整代码:

import csv
import sys
from PyQt4 import QtCore

from PyQt4 import QtGui


class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.filterall = QtGui.QTableWidget(self)
        self.filterall.setColumnCount(0)
        self.filterall.setRowCount(0)
        self.verticalLayout.addWidget(self.filterall)

        self.loadAll()
        self.horizontalHeader = self.filterall.horizontalHeader()
        self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)
        self.keywords = dict([(i, []) for i in range(self.filterall.columnCount())])
        self.checkBoxs = []
        self.col = None

    def slotSelect(self, state):

        for checkbox in self.checkBoxs:
            checkbox.setChecked(QtCore.Qt.Checked == state)

    def on_view_horizontalHeader_sectionClicked(self, index):
        # self.clearFilter()
        self.menu = QtGui.QMenu(self)
        self.col = index

        data_unique = []

        self.checkBoxs = []

        checkBox = QtGui.QCheckBox("Select all", self.menu)
        checkableAction = QtGui.QWidgetAction(self.menu)
        checkableAction.setDefaultWidget(checkBox)
        self.menu.addAction(checkableAction)
        checkBox.setChecked(True)
        checkBox.stateChanged.connect(self.slotSelect)

        for i in range(self.filterall.rowCount()):
            if not self.filterall.isRowHidden(i):
                item = self.filterall.item(i, index)
                if item.text() not in data_unique:
                    data_unique.append(item.text())
                    checkBox = QtGui.QCheckBox(item.text(), self.menu)
                    checkBox.setChecked(True)
                    checkableAction = QtGui.QWidgetAction(self.menu)
                    checkableAction.setDefaultWidget(checkBox)
                    self.menu.addAction(checkableAction)
                    self.checkBoxs.append(checkBox)

        btn = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
                                     QtCore.Qt.Horizontal, self.menu)
        btn.accepted.connect(self.menuClose)
        btn.rejected.connect(self.menu.close)
        checkableAction = QtGui.QWidgetAction(self.menu)
        checkableAction.setDefaultWidget(btn)
        self.menu.addAction(checkableAction)

        headerPos = self.filterall.mapToGlobal(self.horizontalHeader.pos())

        posY = headerPos.y() + self.horizontalHeader.height()
        posX = headerPos.x() + self.horizontalHeader.sectionPosition(index)
        self.menu.exec_(QtCore.QPoint(posX, posY))

    def menuClose(self):
        self.keywords[self.col] = []
        for element in self.checkBoxs:
            if element.isChecked():
                self.keywords[self.col].append(element.text())
        self.filterdata()
        self.menu.close()

    def loadAll(self):
        with open("Rts.csv", "rb") as inpfil:
            reader = csv.reader(inpfil, delimiter=',')
            csheader = reader.next()
            ncol = len(csheader)
            data = list(reader)
            row_count = len(data)

            self.filterall.setRowCount(row_count)
            self.filterall.setColumnCount(ncol)
            self.filterall.setHorizontalHeaderLabels(QtCore.QString('%s' % ', '.join(map(str, csheader))).split(","))

            for ii in range(0, row_count):
                mainins = data[ii]
                for var in range(0, ncol):
                    self.filterall.setItem(ii, var, QtGui.QTableWidgetItem(mainins[var]))

    def clearFilter(self):
        for i in range(self.filterall.rowCount()):
            self.filterall.setRowHidden(i, False)

    def filterdata(self):

        columnsShow = dict([(i, True) for i in range(self.filterall.rowCount())])

        for i in range(self.filterall.rowCount()):
            for j in range(self.filterall.columnCount()):
                item = self.filterall.item(i, j)
                if self.keywords[j]:
                    if item.text() not in self.keywords[j]:
                        columnsShow[i] = False
        for key, value in columnsShow.iteritems():
            self.filterall.setRowHidden(key, not value)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

【讨论】:

  • 非常感谢...它工作得很好,正如我预期的那样。但有一个问题。我已经有一个用 QtDesigner 制作的 GUI。如果我在那里添加这个类会产生任何问题吗?
  • @PradyumnaCheerala 我用你展示的代码和我的项目在几个小时内上传了一个项目到 github。
  • 我们可以将过滤后的表格值写入csv文件吗?如果是这样,我们怎么能?
  • 我正在尝试打印数据。我得到的是真假状态。所以我不能把它写进csv。如何检索正在显示的数据?这样我就可以将其保存在 csv 文件中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2018-02-24
相关资源
最近更新 更多