从不同类调用方法以重新加载QTableWidg

2024-04-26 10:58:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有问题如何更新QTable小部件而不关闭窗口,因为我想有两个窗口一直打开。QTableWidget中的数据是从数据库加载的。你知道吗

From Main()状态由用户在dispatch_status方法中更新,当按下按钮update时,QMessageWindow出现在屏幕上,用户按“OK”确认。我想通过setRowCount(0)刷新第二个窗口中的信息,并从数据库加载更新的数据

过程py

from PyQt5.QtWidgets import *
import sys, os
from PyQt5.QtCore import QSize, QDate
from PyQt5.QtGui import *
from PyQt5 import uic, Qt, QtCore
from mysql.connector import MySQLConnection, Error
from mysql_dbconfig import read_db_config
from dispatch_report import DispatchReport
import PyQt5


class Main( QMainWindow, QWidget):

    def __init__(self):
        super().__init__()

        uic.loadUi('processor.ui', self)
        self.setWindowTitle("Processor")
        self.UI()
        self.job_loader()

    def UI(self):
        ''' Sets User Interface''' 

        status_list = ['New','On Hold','Selected','Completed']
        self.combo_status.addItems(status_list)
        self.list_jobs_list.itemClicked.connect(self.get_job_no)
        self.btn_update.clicked.connect(self.update_db)
        self.btn_open_dispatch.clicked.connect(self.conn_dispatch)

        self.show()

    def job_loader(self):
        ''' Load jobs to QListWidget'''
        try:  
            db_config = read_db_config()
            conn = MySQLConnection(**db_config)
            cursor = conn.cursor()                 
            if conn.is_connected():
                query = f'''SELECT job FROM jobs'''  
                cursor.execute(query)
                rows = cursor.fetchall()

                for row in rows:
                    self.list_jobs_list.addItem(str(row[0]))              
            else:
                print('Connection failed.')

        except Error as error:
            print(error)

        finally:
            if conn is not None and conn.is_connected():
                cursor.close()
                conn.close()

    def get_job_no(self):
        ''' reads jobNo selected on QListWidget '''
        jobNo = self.list_jobs_list.currentItem().text()
        self.display_current_status(jobNo)

    def get_signal(self, jobNo):
        ''' Getting signal from dispatch QWidget Table'''
        self.display_current_status(jobNo)

    def display_current_status(self, jobNo):
        ''' Displays status and job No '''

        self.lab_jobNo.setText(jobNo)      
        try:  
            db_config = read_db_config()
            conn = MySQLConnection(**db_config)
            cursor = conn.cursor()          

            if conn.is_connected():

                query = f'''SELECT job_status FROM jobs WHERE job = {jobNo}'''  
                cursor.execute(query)
                row = cursor.fetchone()[0]
                print(row)
                self.current_status.setText(row)

            else:
                print('Connection failed.')

        except Error as error:
            print(error)

        finally:
            if conn is not None and conn.is_connected():
                cursor.close()
                conn.close()

    def update_db(self):
        ''' Updates status in database '''
        jobNo =int(self.lab_jobNo.text()) 
        try:  
            db_config = read_db_config()
            conn = MySQLConnection(**db_config)
            cursor = conn.cursor()          

            if conn.is_connected():

                query = f'''UPDATE jobs SET job_status = "{self.combo_status.currentText()}" 
                            WHERE job = {jobNo} ''' 
                cursor.execute(query) 
                conn.commit()

                QMessageBox.information(self,'Status Update','Dispatch Status Updated')

                # <-- Here I would like to refresh Dispatch report -->
                self.dispatch_class = DispatchReport()    
                self.dispatch_class.dispatch_rep

            else:
                print('Connection failed.')

        except Error as error:
            print(error)

        finally:
            if conn is not None and conn.is_connected():
                cursor.close()
                conn.close()


    def conn_dispatch(self):
        self.dispatch = DispatchReport()
        self.dispatch.trigger.connect(self.get_signal)


def main():

    App = QApplication(sys.argv)
    window=Main()
    sys.exit(App.exec_())

if __name__ == '__main__':
    main()

派送.py

from PyQt5.QtWidgets import *
import sys
from PyQt5 import uic, Qt, QtPrintSupport
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import QPrinter, QPrintDialog, QPrintPreviewDialog 
from mysql.connector import MySQLConnection, Error
from mysql_dbconfig import read_db_config
from PyQt5.QtGui import QPixmap, QFont
from PyQt5 import uic, Qt, QtCore


class DispatchReport(QMainWindow, QWidget):
    trigger = QtCore.pyqtSignal(str)

    def __init__(self):
        super(DispatchReport, self).__init__()
        uic.loadUi('dispatch_report.ui',self)
        self.setWindowTitle("Dispatch Report")
        self.UI()
        self.show()

        self.dispatch_rep()

    def UI(self):

        self.table_dispatch.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_dispatch.cellDoubleClicked.connect(self.selected_search)
        self.btn_refresh.clicked.connect(self.dispatch_rep)

        self.table_dispatch.verticalHeader().hide()
        self.table_dispatch.setSortingEnabled(True)

        # set table column number and header description
        self.table_dispatch.setRowCount(0)
        self.table_dispatch.setColumnCount(2)        
        self.table_dispatch.setHorizontalHeaderItem(0, QTableWidgetItem('Job No'))
        self.table_dispatch.setHorizontalHeaderItem(1, QTableWidgetItem('Status'))

    def dispatch_rep(self):
        '''Gets information from database and insert into QTableWidget'''

        self.table_dispatch.setRowCount(0)
        try:  
            db_config = read_db_config()
            conn = MySQLConnection(**db_config)
            cursor = conn.cursor()          

            if conn.is_connected():

                query = "SELECT * FROM jobs "

                cursor.execute(query)
                self.dataQ = cursor.fetchall()

                for row_data in self.dataQ:
                    row_number = self.table_dispatch.rowCount()
                    self.table_dispatch.insertRow(row_number)
                    for column_number, data in enumerate(row_data):
                        self.table_dispatch.setItem(row_number, column_number, QTableWidgetItem(str(data)))

            else:
                print('Connection failed.')

        except Error as error:
            print(error)

        finally:
            if conn is not None and conn.is_connected():
                cursor.close()
                conn.close()


    def selected_search(self):


        row = self.table_dispatch.currentRow()
        search_list = []
        for i in range(2):
            item = self.table_dispatch.item( row, i).text()
            search_list.append(item)


        # Sending signal 
        jobNo = search_list[0]
        self.trigger.emit(jobNo)



def main():

    App = QApplication(sys.argv)
    window=DispatchReport()
    sys.exit(App.exec_())

if __name__ == '__main__':
    main()

当我按下中创建的刷新按钮时,它可以完美地工作派送.py
self.btn_refresh.clicked.connect(self.dispatch_rep) 但是当从Main调用的dispatch_rep不起作用时,新窗口会自动打开和关闭。你知道吗

我是编程新手,非常感谢大家的帮助。 谢谢

编辑 谢谢你的帮助

在该应用程序中,我需要保持两个窗口都打开(如在img上),当我双击QTableWidget dispatch\u report中的行时,proc窗口将更新,并且我可以更改已单击作业的状态。或者我可以在proc窗口中单击QListWidget上的job number 并更改状态。在这两种情况下,更新后,我想得到调度报告窗口更新不关闭,并重新打开它。你知道吗

在上述代码更新后,第二个调度报告窗口打开。你知道吗

是否可以只刷新QTaleWidget到setrowCount(0)并从数据库加载数据而不关闭该窗口?你知道吗

调度_报表.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>618</width>
    <height>845</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>170</x>
      <y>10</y>
      <width>271</width>
      <height>31</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <pointsize>16</pointsize>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
    <property name="text">
     <string>Dispatch Fitting Schedule</string>
    </property>
   </widget>
   <widget class="QTableWidget" name="table_dispatch">
    <property name="geometry">
     <rect>
      <x>30</x>
      <y>70</y>
      <width>301</width>
      <height>461</height>
     </rect>
    </property>
    <property name="gridStyle">
     <enum>Qt::SolidLine</enum>
    </property>
   </widget>
   <widget class="QPushButton" name="btn_refresh">
    <property name="geometry">
     <rect>
      <x>60</x>
      <y>20</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Refresh</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>618</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</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>935</width>
    <height>708</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QListWidget" name="list_jobs_list">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>40</y>
      <width>181</width>
      <height>241</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>240</x>
      <y>70</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>JobNO: </string>
    </property>
   </widget>
   <widget class="QLabel" name="lab_jobNo">
    <property name="geometry">
     <rect>
      <x>280</x>
      <y>70</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>TextLabel</string>
    </property>
   </widget>
   <widget class="QComboBox" name="combo_status">
    <property name="geometry">
     <rect>
      <x>230</x>
      <y>150</y>
      <width>241</width>
      <height>22</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label_2">
    <property name="geometry">
     <rect>
      <x>230</x>
      <y>130</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>Status</string>
    </property>
   </widget>
   <widget class="QPushButton" name="btn_update">
    <property name="geometry">
     <rect>
      <x>400</x>
      <y>190</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Update</string>
    </property>
   </widget>
   <widget class="QLineEdit" name="current_status">
    <property name="geometry">
     <rect>
      <x>230</x>
      <y>100</y>
      <width>113</width>
      <height>20</height>
     </rect>
    </property>
   </widget>
   <widget class="QPushButton" name="btn_open_dispatch">
    <property name="geometry">
     <rect>
      <x>270</x>
      <y>250</y>
      <width>181</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>Open Dispatch Report</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>935</width>
     <height>21</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFIle">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="separator"/>
    <addaction name="actionExit"/>
    <addaction name="separator"/>
   </widget>
   <widget class="QMenu" name="menuTool">
    <property name="title">
     <string>Tool</string>
    </property>
    <addaction name="actionAdd_New_Customer"/>
    <addaction name="actionAdd_New_Job"/>
   </widget>
   <widget class="QMenu" name="menuView">
    <property name="title">
     <string>Reports</string>
    </property>
    <addaction name="action_prod_report"/>
    <addaction name="action_dispatch_report"/>
    <addaction name="actionWeekly_fitting_schedule"/>
   </widget>
   <widget class="QMenu" name="menuSearch">
    <property name="title">
     <string>Search</string>
    </property>
    <addaction name="actionSearch"/>
   </widget>
   <widget class="QMenu" name="menuAbout">
    <property name="title">
     <string>About</string>
    </property>
    <addaction name="action_about"/>
   </widget>
   <addaction name="menuFIle"/>
   <addaction name="menuTool"/>
   <addaction name="menuView"/>
   <addaction name="menuSearch"/>
   <addaction name="menuAbout"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <widget class="QToolBar" name="toolBar">
   <property name="windowTitle">
    <string>toolBar</string>
   </property>
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <action name="actionExit">
   <property name="text">
    <string>Exit</string>
   </property>
  </action>
  <action name="action_prod_report">
   <property name="text">
    <string>Production List</string>
   </property>
  </action>
  <action name="action_dispatch_report">
   <property name="text">
    <string>Dispatch Fitting Schedule</string>
   </property>
  </action>
  <action name="action_about">
   <property name="text">
    <string>info</string>
   </property>
  </action>
  <action name="actionAdd_New_Customer">
   <property name="text">
    <string>Add New Customer</string>
   </property>
  </action>
  <action name="actionAdd_New_Job">
   <property name="text">
    <string>Add New Job</string>
   </property>
  </action>
  <action name="actionAdd_Location">
   <property name="text">
    <string>Add Location</string>
   </property>
  </action>
  <action name="actionWeekly_fitting_schedule">
   <property name="text">
    <string>Weekly Fitting Schedule</string>
   </property>
  </action>
  <action name="actionSearch">
   <property name="text">
    <string>Search</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

enter image description here


Tags: textnamerectimportselfstringactionproperty