事件 - 仅捕获qtablewidget; pyqt5

时间:2018-03-18 13:43:12

标签: python python-3.x pyqt5 qt-designer qtablewidget

我想改变 Key_C keypressevent的行为或仅为 QTableWidget 创建自定义keypressevent处理程序,也导致在QtDesigner中创建的所有表单我想通过代码实现tablemain.py。另外,我发现根据this answer我需要在QtDesigner中宣传我的 QTableWidget ,但我不知道如何正确执行此操作。 所以,再一次主要目标是:

  1. 仅对从QtDesigner表单导入的 QTableWidget 处理 Key_C keyPressEvent,并且只有当我们专注于它时,才将所选单元格复制到剪贴板中。 table.ui table.py tablemain.py 所有文件PSB:
  2. Illustration of the desired state:

    table.ui

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>749</width>
        <height>519</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralwidget">
       <widget class="QTableWidget" name="tableWidget">
        <property name="geometry">
         <rect>
          <x>20</x>
          <y>10</y>
          <width>611</width>
          <height>371</height>
         </rect>
        </property>
        <property name="alternatingRowColors">
         <bool>true</bool>
        </property>
        <property name="gridStyle">
         <enum>Qt::DotLine</enum>
        </property>
        <row>
         <property name="text">
          <string>1</string>
         </property>
        </row>
        <column>
         <property name="text">
          <string>1st column</string>
         </property>
        </column>
        <column>
         <property name="text">
          <string>2nd column</string>
         </property>
        </column>
        <column>
         <property name="text">
          <string>3rd column</string>
         </property>
        </column>
       </widget>
      </widget>
      <widget class="QMenuBar" name="menubar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>749</width>
         <height>19</height>
        </rect>
       </property>
      </widget>
      <widget class="QStatusBar" name="statusbar"/>
     </widget>
     <resources/>
     <connections/>
    </ui>
    

    table.py

    # -*- coding: utf-8 -*-
    
    # Form implementation generated from reading ui file 'table.ui'
    #
    # Created by: PyQt5 UI code generator 5.9
    #
    # WARNING! All changes made in this file will be lost!
    
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName("MainWindow")
            MainWindow.resize(749, 519)
            self.centralwidget = QtWidgets.QWidget(MainWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
            self.tableWidget.setGeometry(QtCore.QRect(20, 10, 611, 371))
            self.tableWidget.setAlternatingRowColors(True)
            self.tableWidget.setGridStyle(QtCore.Qt.DotLine)
            self.tableWidget.setObjectName("tableWidget")
            self.tableWidget.setColumnCount(3)
            self.tableWidget.setRowCount(1)
            item = QtWidgets.QTableWidgetItem()
            self.tableWidget.setVerticalHeaderItem(0, item)
            item = QtWidgets.QTableWidgetItem()
            self.tableWidget.setHorizontalHeaderItem(0, item)
            item = QtWidgets.QTableWidgetItem()
            self.tableWidget.setHorizontalHeaderItem(1, item)
            item = QtWidgets.QTableWidgetItem()
            self.tableWidget.setHorizontalHeaderItem(2, item)
            MainWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(MainWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 749, 19))
            self.menubar.setObjectName("menubar")
            MainWindow.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(MainWindow)
            self.statusbar.setObjectName("statusbar")
            MainWindow.setStatusBar(self.statusbar)
    
            self.retranslateUi(MainWindow)
            QtCore.QMetaObject.connectSlotsByName(MainWindow)
    
        def retranslateUi(self, MainWindow):
            _translate = QtCore.QCoreApplication.translate
            MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
            item = self.tableWidget.verticalHeaderItem(0)
            item.setText(_translate("MainWindow", "1"))
            item = self.tableWidget.horizontalHeaderItem(0)
            item.setText(_translate("MainWindow", "1st column"))
            item = self.tableWidget.horizontalHeaderItem(1)
            item.setText(_translate("MainWindow", "2nd column"))
            item = self.tableWidget.horizontalHeaderItem(2)
            item.setText(_translate("MainWindow", "3rd column"))
    

    tablemain.py

    import sys
    import os
    import io
    import time
    from table import *
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class MyWin(QtWidgets.QMainWindow):
    
        def __init__(self, parent=None):
            QtWidgets.QWidget.__init__(self, parent)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            self.clipboard = QtWidgets.QApplication.clipboard
            self.ui.tableWidget.keyPressEvent = self.tableWidgetSentKeyPressEvent
    
    
        def tableWidgetSentKeyPressEvent(self, event):
            if event.key() == QtCore.Qt.Key_C:
                self.copy()
            return QtWidgets.QTableWidget.keyPressEvent(self.ui.tableWidget, event)
    
        # def keyPressEvent(self, e):
    
        #     """
        #     Captures keypresses to handle copy, cut, and paste.
    
        #     Arguments:
        #     e   --  a QKeyEvent.
        #     """
    
            # if e.key() == QtCore.Qt.Key_Delete:
            #     self._clear()
            #     e.ignore()
            # elif e.modifiers() == QtCore.Qt.ControlModifier and e.key() == \
            #     QtCore.Qt.Key_X:
            #     self.cut()
            #     e.ignore()
            # elif e.modifiers() == QtCore.Qt.ControlModifier and e.key() == \
            #     QtCore.Qt.Key_C:
            #     self.copy()
            #     e.ignore()
            # elif e.modifiers() == QtCore.Qt.ControlModifier and e.key() == \
            #     QtCore.Qt.Key_V:
            #     self.paste()
            #     e.ignore()
            # else:
            #     QtWidgets.QTableWidget.keyPressEvent(self, e)
    
        def copy(self):
    
            """Copies data from the table into the clipboard."""
    
            _range =  self.ui.tableWidget.selectedRanges()[0]
            rows = []
            for row in range(_range.topRow(), _range.bottomRow()+1):
                columns = []
                for column in range(_range.leftColumn(), _range.rightColumn()+1):
                    item = self.ui.tableWidget.item(row, column)
                    if item != None:
                        value = str(item.text())
                    else:
                        value = u''
                    columns.append(value)
                rows.append(u'\t'.join(columns))
            selection = u'\n'.join(rows)
            self.clipboard().setText(selection)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        myapp = MyWin()
        myapp.show()
        sys.exit(app.exec_())
    

0 个答案:

没有答案