从上下文菜单qlineedit-pyqt更新Qtablewidget

时间:2012-08-14 19:38:18

标签: python pyqt qtablewidget

我有一个QTableWidget我希望从QLinEdit嵌入到上下文菜单中更新。现在,在QLinEdit中输入服务器名称,当按下该键时,程序扫描MySQL数据库以查看服务器名称是否在其中,如果是,则用数据更新QTableWidget从服务器名称表中,如果找不到,则会出现错误messageBox

我不能做的是连接上下文菜单QLinEdit以更新QTableWidget

QTableWidget连接到上下文菜单:

self.table1.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.table1.customContextMenuRequested.connect(self.handleHeaderMenu)

文本菜单:

    def handleHeaderMenu(self, pos):
        self.custom_choice = QtGui.QLineEdit()
        self.menu = QtGui.QMenu()
        self.custom_choice.setPlaceholderText("Server")
        self.wac = QtGui.QWidgetAction(self.menu)
        self.wac.setDefaultWidget(self.custom_choice)
        self.menu.setStyleSheet("QMenu::item {background-color: #264F7D;color: white; font-weight:bold;}")
        self.menu.addAction("Choose Server to Monitor:")
        self.menu.addSeparator()
        self.actionJuliet = self.menu.addAction('Juliet')
        self.actionJulietleft = self.menu.addAction('JulietLeft')
        self.actionPong = self.menu.addAction('Pong')
        self.actionHulk = self.menu.addAction('Hulk')
        self.actionCustom = self.menu.addAction(self.wac)
        action = self.menu.exec_(QtGui.QCursor.pos())
        self.connect(self.custom_choice, QtCore.SIGNAL("returnPressed()"),self.refreshdata)

数据获取器/扫描器:

def get_data(self):
    self.tx = self.custom_choice.text()
    self.model.execute("show TABLES;")
    table_array = []
    table_names = self.model.fetchall()
    for lines in table_names:
        lines = str(lines)
        lines = lines.strip("()""''"",")
        table_array.append(lines)
    if any("%s" % self.tx in s for s in table_array):
        table_name = self.tx
        self.model.execute("""SELECT computer_name 
                              FROM %s""" % (table_name))
        new_user_name = self.model.fetchall()
        print new_user_name,table_name
        self.model.execute("""SELECT idle_time 
                              FROM %s""" % (table_name))
        new_idle = self.model.fetchall()
        self.model.execute("""SELECT files_opened 
                              FROM %s""" % (table_name))
        new_files = self.model.fetchall()
        self.model.execute("""SELECT active_time 
                              FROM %s""" % (table_name))
        new_active = self.model.fetchall()
        self.model.execute("""SELECT session_type 
                           FROM %s""" % (table_name))
        new_session = self.model.fetchall()
        self.model.execute("""SELECT cpu 
                           FROM %s""" % (table_name))
        new_cpu_load = self.model.fetchall()
        self.model.execute("""SELECT avg_disk_queue 
                           FROM %s""" % (table_name))
        new_disk_queue_load = self.model.fetchall()
        new_data_user = [item0[0] for item0 in new_user_name]
        new_data_idle = [item1[0] for item1 in new_idle]
        new_data_files = [item2[0] for item2 in new_files]
        new_data_active = [item3[0] for item3 in new_active]
        new_data_session = [item4[0] for item4 in new_session]
        new_data_cpu_load = [item5[0] for item5 in new_cpu_load]
        new_data_disk_queue_load = [item6[0] for item6 in new_disk_queue_load]
        self.lista = new_data_user
        self.listb = new_data_disk_queue_load
        self.listc = new_data_cpu_load
        self.listd = new_data_active
        self.liste = new_data_files
        self.listf = new_data_session
        self.listg = new_data_idle  
        self.mystruct2 = {'A':self.lista, 'B':self.listb, 'C':self.listc,'E':self.liste,'D':self.listd,'F':self.listf,'G':self.listg} 

1 个答案:

答案 0 :(得分:0)

handleHeaderMenu的设计有点偏。当前结构化方式的主要问题之一是,在弹出菜单完成后,您将信号连接到QLineEdit 。所以你会错过那个信号。

action = self.menu.exec_(QtGui.QCursor.pos())
self.connect(self.custom_choice, 
                QtCore.SIGNAL("returnPressed()"),
                self.refreshdata)

QMenu.exec_()是一个阻止通话。它启动菜单的事件循环并等待它完成。一旦关闭并返回所选的QAction,您就可以建立连接。在下一点之后我会对此进行修正......

每次从头开始构建的菜单不必保存到成员属性并在外部使用。有两种方法可以进行自定义弹出菜单。如果它主要是静态的,那么你可以在类init中构建它一次,或者使它成为自己的类,然后只重用实例。或者在你的情况下,你可以每次建立它,这很好。但是,不是依赖于对菜单组件的持久引用和使用信号,为什么不只是暂时构建它,并明确地处理结果?

def handleHeaderMenu(self, pos):
    menu = QtGui.QMenu()
    menu.setStyleSheet("""
        QMenu::item {
            background-color: #264F7D;
            color: white; 
            font-weight:bold;}
    """)
    text = menu.addAction("Choose Server to Monitor:")
    text.setEnabled(False)
    menu.addSeparator()

    actionJuliet = menu.addAction('Juliet')
    actionJulietleft = menu.addAction('JulietLeft')
    actionPong = menu.addAction('Pong')
    actionHulk = menu.addAction('Hulk')

    wac = QtGui.QWidgetAction(menu)
    custom_choice = QtGui.QLineEdit()
    custom_choice.setPlaceholderText("Server")
    wac.setDefaultWidget(custom_choice)
    menu.addAction(wac)

    menu.setActiveAction(wac)
    custom_choice.returnPressed.connect(wac.trigger)

    action = menu.exec_(QtGui.QCursor.pos())
    if action:
        if action == wac:
            self.tx = str(custom_choice.text()).strip()
        else:
            self.tx = str(action.text())

        self.refreshdata()

def refreshdata(self):
    print self.tx

这里我们只为菜单创建一堆临时小部件,这些小部件将被垃圾收集。显示菜单后,我们检查返回的操作,然后手动设置我们的表属性,并调用refresh。此外,我们需要设置来自自定义QLineEdit的信号以在内部触发其窗口小部件操作。

最后,每次要加载这些数据时,是否真的有必要进行8次sql查询和一大堆数据重组?这可以高度简化:

def get_data(self):

    table_check = """
        SELECT table_name FROM information_schema.tables 
        WHERE table_schema = %s AND table_name = %s 
        """

    table_name = self.tx
    count = self.model.execute(table_check, (self.theDatabaseName, table_name))
    if not count:
        # warn the user that the table name does not exist
        warn_user_of_bad_table()
        return

    sql = """
        SELECT 
            computer_name, idle_time, files_opened, 
            active_time, session_type, cpu, avg_disk_queue
        FROM %s 
        """ % table_name

    count = self.model.execute(sql)
    if not count:
        warn_database_error()
        return

    results = self.model.fetchall()
    user, idle , files, active, session, cpu, disk = zip(*results)
    self.lista = user
    self.listb = disk
    self.listc = cpu
    self.listd = active
    self.liste = files
    self.listf = session
    self.listg = idle  
    self.mystruct2 = {
        'A' : self.lista, 
        'B' : self.listb, 
        'C' : self.listc,
        'E' : self.liste,
        'D' : self.listd,
        'F' : self.listf,
        'G' : self.listg
    }

这里只需要两个查询。第一个非常简单的方法是通过使用方案检查表是否存在,而不是通过一个大的SHOW TABLES输出进行解析。第二个在一个查询中获取所有数据(作为一堆行,然后使用zip将它们重新组合成列。