mdiArea.subWindowActivated和qtablewidget.itemActivated之间的冲突

时间:2018-10-21 19:55:43

标签: python pyqt5

我有一个QMainWindow。'它有一个菜单FaceCapture-> Update'。在 init

处有以下信号

enter image description here

self.mdiArea.subWindowActivated.connect(self.updateMenus)

在单击更新菜单上,将打开mdi QDialog。该表单具有QtableWidget和“搜索”按钮。在 init

处有以下信号

enter image description here

self.employeeTableWidget.itemActivated.connect(self.employeeTableWidgetClicked)

在点击“搜索”按钮后,表格中填充了几行

enter image description here

当我单击表的任何行时,将触发mdiArea.subWindowActivated而不是employeeTableWidget.itemActivated。

这是代码-两个.py文件。运行faceRecognition.py

faceRecognitiontion.py

import sys
import sqlite3
import PyQt5
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow
import cv2
import os
from PIL import Image
from PIL.ImageQt import ImageQt
import numpy as np
import pandas as pd

from PyQt5.uic import loadUi
from EmployeeAdd import photo,faceAdd
from EmployeeUpdate import photo,faceUpdate

from PyQt5.QtCore import (QFile, QFileInfo, QPoint, QSettings, QSignalMapper,
    QSize, QTextStream, Qt)
from PyQt5.QtGui import QIcon, QKeySequence
from PyQt5.QtWidgets import (QAction, QApplication, QFileDialog, QMainWindow,
    QMdiArea, QMessageBox, QTextEdit, QWidget)


class faceRecognition(QMainWindow):
def __init__(self, parent=None):
    super(faceRecognition, self).__init__(parent)
    #self.statusBar = ""
    self.path = ""
    self.readPath = ""
    #self.stackedImage = np.zeros([1, 1, 3], np.uint8)
    #self.img = []
    #xx = Ui_MainWindow()
    #print("hh",xx.mdiArea)
    loadUi('faceRecognition.ui', self)
    self.faceAddChild = None
    self.faceUpdateChild = None
    self.showMaximized()
    self.mdiArea = QMdiArea()
    self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
    self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
    self.setCentralWidget(self.mdiArea)

    self.mdiArea.subWindowActivated.connect(self.updateMenus)
    self.windowMapper = QSignalMapper(self)
    self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow)

    self.buildActions()
    self.setWindowTitle("Face Recognition")
    self.setWindowIcon(QtGui.QIcon('rensol-logo.png'))

    self.updateMenus()
    #self.windowMenu.aboutToShow.connect(self.updateWindowMenu)

def addFaceTrg(self):
    try:
        if self.faceAddChild:
            print("i am in addfacetrg")
            #self.raise_()
            #self.faceUpdateChild.activateWindow()

#self.mdiArea.setActiveSubWindow(self.mdiArea.activeSubWindow())
            self.faceAddChild.show()
            self.faceAddChild.showMaximized()
            return 0
        print("addFaceTrg")
        activeChild = self.mdiArea.activeSubWindow()

        #if activeChild:
        #    print("active sub", type(activeChild), type("Employee Update"), type(activeChild.windowTitle()))
        #    if activeChild.windowTitle() == "Employee Add" or "Employee Update":
        #        print("i am dialog",activeChild.windowTitle )
        #        return 0
        self.faceAddChild = faceAdd()
        self.mdiArea.addSubWindow(self.faceAddChild)
        self.faceAddChild.show()
        self.faceAddChild.showMaximized()
        #self.updateWindowMenu()
        print("i am exiting addface")
    except Exception as exp:
        print("addFaceTrg",str(exp))

def updateFaceTrg(self):
    try:
        if self.faceUpdateChild:
            print("i am in jjjjj")
            #self.raise_()
            #self.faceUpdateChild.activateWindow()
            #self.mdiArea.setActiveSubWindow(self.mdiArea.activeSubWindow())
            self.faceUpdateChild.show()
            self.faceUpdateChild.showMaximized()
            return 0
        print("updateFaceTrg")
        activeChild = self.mdiArea.activeSubWindow()

        #if activeChild:
        #    print("active sub", type(activeChild), type("Employee Update"), type(activeChild.windowTitle()))
        #    if activeChild.windowTitle() == "Employee Update":
        #        print("i am dialog",activeChild.windowTitle )
        #        return 0
        self.faceUpdateChild = faceUpdate()
        self.mdiArea.addSubWindow(self.faceUpdateChild)
        self.faceUpdateChild.show()
        self.faceUpdateChild.showMaximized()
        #self.updateWindowMenu()
        print("i am exiting update face")
    except Exception as exp:
        print("updateFaceTrg",str(exp))

def updateMenus(self):
    try:
        print("i am in updatemenus")
        hasMdiChild = (self.activeMdiChild() is not None)
        print("has mdi child", hasMdiChild)
        #self.saveAct.setEnabled(hasMdiChild)
        #self.saveAsAct.setEnabled(hasMdiChild)
        #self.pasteAct.setEnabled(hasMdiChild)
        self.closeAct.setEnabled(hasMdiChild)
        self.closeAllAct.setEnabled(hasMdiChild)
        #self.tileAct.setEnabled(hasMdiChild)
        #self.cascadeAct.setEnabled(hasMdiChild)
        #self.nextAct.setEnabled(hasMdiChild)
        #self.previousAct.setEnabled(hasMdiChild)
        #self.separatorAct.setVisible(hasMdiChild)

        #hasSelection = (self.activeMdiChild() is not None and
        #                self.activeMdiChild().textCursor().hasSelection())
        #self.cutAct.setEnabled(hasSelection)
        #self.copyAct.setEnabled(hasSelection)
    except Exception as exp:
        print("updateMenus",str(exp))

def updateWindowMenu(self):
    try:
        self.windowMenu.clear()
        self.windowMenu.addAction(self.closeAct)
        self.windowMenu.addAction(self.closeAllAct)
        self.windowMenu.addSeparator()
        #self.windowMenu.addAction(self.tileAct)
        #self.windowMenu.addAction(self.cascadeAct)
        #self.windowMenu.addSeparator()
        #self.windowMenu.addAction(self.nextAct)
        #self.windowMenu.addAction(self.previousAct)
        #self.windowMenu.addAction(self.separatorAct)
        print("i am in update window menus")
        windows = self.mdiArea.subWindowList()
        #self.separatorAct.setVisible(len(windows) != 0)

        for i, window in enumerate(windows):
            print("i am in enu win",i)
            child = window.widget()

            text = "%d %s" % (i + 1, window.windowTitle())
            if i < 9:
                text = '&' + text
                print(text)

            action = self.windowMenu.addAction(text)
            action.setCheckable(True)
            action.setChecked(child is self.activeMdiChild())
            action.triggered.connect(self.windowMapper.map)
            self.windowMapper.setMapping(action, window)
    except Exception as exp:
        print("updateWindowMenu",str(exp))

def buildActions(self):
    self.addFaceAct.triggered.connect(self.addFaceTrg)
    self.updateFaceAct.triggered.connect(self.updateFaceTrg)
    self.windowMenu.aboutToShow.connect(self.updateWindowMenu)
    self.closeAllAct.triggered.connect(self.closeAllTrg)
    self.closeAct.triggered.connect(self.closeTrg)
    #self.separatorAct = QAction(self)
    #self.separatorAct.setSeparator(True)

    #self.openAct = QAction(QIcon(':/images/open.png'), "&Open...", self,
    #        shortcut=QKeySequence.Open, statusTip="Open an existing file",
    #        triggered=self.open)

def closeAllTrg(self):
    self.mdiArea.closeAllSubWindows()
    self.resetActionVariables()

def closeTrg(self):
    #activeChild = self.mdiArea.activeSubWindow()
    #print("active sub", type(activeChild), type("Employee Update"), type(activeChild.windowTitle()))

    self.mdiArea.closeActiveSubWindow()
    self.resetActionVariables()

def resetActionVariables(self):
    self.faceAddChild = None
    self.faceUpdateChild = None

def activeMdiChild(self):
    activeSubWindow = self.mdiArea.activeSubWindow()
    if activeSubWindow:
        return activeSubWindow.widget()
    return None

def setActiveSubWindow(self, window):
    if window:
        self.mdiArea.setActiveSubWindow(window)


def main():
    app = PyQt5.QtWidgets.QApplication(sys.argv)
    window = faceRecognition()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

EmployeeUpdate.py

import sqlite3
import sys
import os
import gc

import PyQt5
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QDialog, QTableWidget, QTableWidgetItem, QMainWindow, QApplication, QWidget, QAction, \
QVBoxLayout, QPushButton, QMainWindow

from PyQt5.uic import loadUi
from EmployeeAdd import photo



class faceUpdate(QDialog):
def __init__(self, parent=None):
    super(faceUpdate, self).__init__(parent)

    self.path = ""
    self.readPath = ""
    self.stackedImage = np.zeros([1, 1, 3], np.uint8)
    self.img = []

    loadUi('EmployeeUpdate.ui', self)
    #self.statusBar = QtWidgets.QStatusBar()
    #self.setWindowTitle("Employee Update")
    #self.setWindowIcon(QtGui.QIcon('rensol-logo.png'))

    self.searchButton.clicked.connect(self.searchButtonClicked)
    self.employeeTableWidget.itemClicked.connect(self.employeeTableWidgetClicked)
    # self.employeeTableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)

    self.connection = sqlite3.connect("FaceRecognition.db")
    self.connectionCursor = self.connection.cursor()
    #self.showButtonInGrid()

@pyqtSlot()
def showButtonInGrid(self):
    btn = QPushButton(self.employeeTableWidget)
    btn.setText('Del')
    btn2 = QPushButton(self.employeeTableWidget)
    rowNo = self.employeeTableWidget.rowCount
    #for i in range(self.employeeTableWidget.rowCount()):
    print("i am in showButtonInGrid")
    self.employeeTableWidget.setCellWidget(1, 10, btn)
    self.employeeTableWidget.setCellWidget(2, 10, btn2)

def employeeTableWidgetClicked(self):
    try:
        print("hellogggggg")
        #self.statusBar().showMessage("jjj")
        item = self.employeeTableWidget.selectedItems()

        rowNo = item[0].row()
        print("row no is", rowNo)
        identifier = item[0].text()
        # xx = self.employeeTableWidget.cellWidget(rowNo,0)
        identifier = self.employeeTableWidget.item(rowNo, 0).text()
        # print((xx.currentText))
        self.path = os.path.dirname(os.path.abspath(__file__))

        os.chdir(self.path)
        self.readPath = "./Images/" + identifier + "/"

        #print(self.employeeTableWidget.selectionModel().selectedIndexes())
        if item[0].column() == 10:
            print("kk")
        if item[0].column() <= 9:
            #print(" i am before imageLabel.clear")
            #self.imageLabel.clear()
            #print(" i am after imageLabel.clear")

            print("read path", self.readPath)
            photoObj = photo(self.readPath)
            if not photoObj.attachImage(self.imageLabel):
                self.statusBar().showMessage("")
            os.remove(self.readPath + "a.jpg")
            del photoObj
            gc.collect()
    except Exception as exp:
        print(str(exp))
        self.ErrorBar.setText(str(exp))

def searchButtonClicked(self):
    searchFields = [self.idText.text(), self.firstNameText.text(), self.lastNameText.text()]
    print(searchFields)
    result = self.getEmployees(searchFields)
    self.displayEmployeeTableWidget(result)

def getEmployees(self,searchFields):
    try:
        #query = """select * from employee where Id = ? or FirstName = ? or LastName = ?""", str(searchFields[0]), str(searchFields[1]), str(searchFields[2])
        #print(query)
        result = self.connectionCursor.execute("""select * from employee where Id = ? or FirstName = ? or LastName = ? """, \
                                     (str(searchFields[0]), str(searchFields[1]), str(searchFields[2])))
        ##query = "select * from employee"
        ##result = self.connection.execute(query)
        #data = result.fetchall()
        #print(len(data))
        print("i am in get employee")
        #print(result.rowcount)
        return result

    except Exception as exp:
        print(str(exp))
        self.ErrorBar.setText(str(exp))
        return 0

def displayEmployeeTableWidget(self, result):
    try:
        self.employeeTableWidget.setRowCount(0)
        for rowNumber, rowData in enumerate(result):
            print("row data is",rowNumber,rowData)
            self.employeeTableWidget.insertRow(rowNumber)
            for columnNumber, data in enumerate(rowData):
                print("data is",columnNumber,data)
                self.employeeTableWidget.setItem(rowNumber, columnNumber,
                                                 QtWidgets.QTableWidgetItem(str(data)))
        #print(str(data))
        #print(self.employeeTableWidget.column(QtWidgets.QTableWidgetItem(1)))
        #self.employeeTableWidget = self.employeeTableWidget.insertRow(2)
        # disable Id column of the table
        for i in range(self.employeeTableWidget.rowCount()):
            #for j in range(10):
            print("i am in for")
            #item = QtWidgets.QTableWidgetItem(str(i * self.employeeTableWidget.columnCount()))
            #item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.employeeTableWidget.item(i,0).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
    except Exception as exp:
        print(str(exp))
        self.ErrorBar.setText(str(exp))

def main():
    app = PyQt5.QtWidgets.QApplication(sys.argv)
    window = faceUpdate()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

EmployeeUpdate.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="windowModality">
   <enum>Qt::ApplicationModal</enum>
  </property>
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1165</width>
    <height>684</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Employee Update</string>
  </property>
  <property name="modal">
   <bool>true</bool>
  </property>
  <widget class="QTableWidget" name="employeeTableWidget">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>90</y>
     <width>1141</width>
     <height>251</height>
    </rect>
   </property>
   <property name="alternatingRowColors">
    <bool>true</bool>
   </property>
   <property name="rowCount">
    <number>7</number>
   </property>
   <property name="columnCount">
    <number>11</number>
   </property>
   <attribute name="horizontalHeaderShowSortIndicator" stdset="0">
    <bool>true</bool>
   </attribute>
   <row/>
   <row/>
   <row/>
   <row/>
   <row/>
   <row/>
   <row/>
   <column>
    <property name="text">
     <string>Id</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>First Name</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Last Name</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Address1</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Address2</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>City</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>State</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Pin</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Date of Birth</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Gender</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <column>
    <property name="text">
     <string>Photo</string>
    </property>
    <property name="font">
     <font>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
   </column>
   <item row="0" column="0">
    <property name="text">
     <string/>
    </property>
   </item>
  </widget>
  <widget class="QLabel" name="idLabel">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>30</y>
     <width>16</width>
     <height>16</height>
    </rect>
   </property>
   <property name="text">
    <string>Id</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="idText">
   <property name="geometry">
    <rect>
     <x>40</x>
     <y>30</y>
     <width>113</width>
     <height>20</height>
    </rect>
   </property>
  </widget>
  <widget class="QLabel" name="firstNameLabel">
   <property name="geometry">
    <rect>
     <x>160</x>
     <y>30</y>
     <width>51</width>
     <height>16</height>
    </rect>
   </property>
   <property name="text">
    <string>First Name</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="firstNameText">
   <property name="geometry">
    <rect>
     <x>220</x>
     <y>30</y>
     <width>113</width>
     <height>20</height>
    </rect>
   </property>
  </widget>
  <widget class="QLabel" name="lastNameLabel">
   <property name="geometry">
    <rect>
     <x>340</x>
     <y>30</y>
     <width>51</width>
     <height>16</height>
    </rect>
   </property>
   <property name="text">
    <string>Last Name</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="lastNameText">
   <property name="geometry">
    <rect>
     <x>400</x>
     <y>30</y>
     <width>113</width>
     <height>20</height>
    </rect>
   </property>
   <property name="text">
    <string>1</string>
   </property>
  </widget>
  <widget class="QPushButton" name="searchButton">
   <property name="geometry">
    <rect>
     <x>530</x>
     <y>30</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>Search</string>
   </property>
  </widget>
  <widget class="QLabel" name="imageLabel">
   <property name="geometry">
    <rect>
     <x>370</x>
     <y>350</y>
     <width>410</width>
     <height>235</height>
    </rect>
   </property>
   <property name="autoFillBackground">
    <bool>false</bool>
   </property>
   <property name="styleSheet">
    <string notr="true">font: 20pt &quot;MS Shell Dlg 2&quot;;</string>
   </property>
   <property name="frameShape">
    <enum>QFrame::Box</enum>
   </property>
   <property name="text">
    <string>View Photo</string>
   </property>
   <property name="textFormat">
    <enum>Qt::AutoText</enum>
   </property>
   <property name="scaledContents">
    <bool>false</bool>
   </property>
   <property name="alignment">
    <set>Qt::AlignCenter</set>
   </property>
  </widget>
  <widget class="QLabel" name="ErrorBar">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>620</y>
     <width>601</width>
     <height>31</height>
    </rect>
   </property>
   <property name="text">
    <string/>
   </property>
   <property name="wordWrap">
    <bool>true</bool>
   </property>
  </widget>
 </widget>
 <tabstops>
  <tabstop>idText</tabstop>
  <tabstop>firstNameText</tabstop>
  <tabstop>lastNameText</tabstop>
  <tabstop>searchButton</tabstop>
  <tabstop>employeeTableWidget</tabstop>
 </tabstops>
 <resources/>
 <connections/>
</ui>

FaceRecognitiontion.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>1190</width>
    <height>714</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string/>
  </property>
  <widget class="QWidget" name="centralwidget"/>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1190</width>
     <height>21</height>
    </rect>
   </property>
   <widget class="QMenu" name="faceCaptureMenu">
    <property name="title">
     <string>&amp;Face Capture</string>
    </property>
    <addaction name="addFaceAct"/>
    <addaction name="updateFaceAct"/>
   </widget>
   <widget class="QMenu" name="trainModelMenu">
    <property name="title">
     <string>Train &amp;Model</string>
    </property>
   </widget>
   <widget class="QMenu" name="predictMenu">
    <property name="title">
     <string>&amp;Predict</string>
    </property>
   </widget>
   <widget class="QMenu" name="windowMenu">
    <property name="title">
     <string>&amp;Window</string>
    </property>
   </widget>
   <addaction name="faceCaptureMenu"/>
   <addaction name="trainModelMenu"/>
   <addaction name="predictMenu"/>
   <addaction name="windowMenu"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="addFaceAct">
   <property name="text">
    <string>&amp;Add</string>
   </property>
   <property name="statusTip">
    <string>Capture photo of the face</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+A</string>
   </property>
  </action>
  <action name="updateFaceAct">
   <property name="text">
    <string>&amp;Update</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+U</string>
   </property>
  </action>
  <action name="closeAct">
   <property name="text">
    <string>&amp;Close</string>
   </property>
  </action>
  <action name="closeAllAct">
   <property name="text">
    <string>Close &amp;All</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

0 个答案:

没有答案