Ejemplo n.º 1
1
    def setupModels(self):
        """
            Initialize all the application models
        """
        # setup slaveModel
        self.sModel = ssModel(self)
        self.sModel.setTable(QString("magaslave"))
        self.sModel.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.sModel.setHeaderData(DATAINS, Qt.Horizontal, QVariant("DataIns"))
        self.sModel.setHeaderData(ABBI, Qt.Horizontal, QVariant("Abbi"))
        self.sModel.setHeaderData(ANGRO, Qt.Horizontal, QVariant("Angro"))
        self.sModel.setHeaderData(DESC, Qt.Horizontal, QVariant("Desc"))
        self.sModel.setHeaderData(QT, Qt.Horizontal, QVariant("Qt"))
        self.sModel.setHeaderData(IMP, Qt.Horizontal, QVariant("Imp"))
        self.sModel.setHeaderData(EQUIV, Qt.Horizontal, QVariant("Equiv"))
        self.sModel.setHeaderData(MMID, Qt.Horizontal, QVariant("ScaffId"))
        self.sModel.setHeaderData(FATT, Qt.Horizontal, QVariant("Fatt"))
        self.sModel.setHeaderData(NOTE, Qt.Horizontal, QVariant("Note"))
        self.sModel.setSort(DATAINS, Qt.AscendingOrder)
        self.sModel.setEditStrategy(QSqlTableModel.OnRowChange)
        self.sModel.select()

        # setup masterModel
        self.mModel = QSqlTableModel(self)
        self.mModel.setTable(QString("magamaster"))
        self.mModel.setSort(SCAFF, Qt.AscendingOrder)
        self.mModel.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.mModel.setHeaderData(SCAFF, Qt.Horizontal, QVariant("Scaff"))
        self.mModel.select()

        # setup findModel
        self.fModel = QSqlRelationalTableModel(self)
        self.fModel.setTable(QString("magaslave"))
        self.fModel.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.fModel.setHeaderData(DATAINS, Qt.Horizontal, QVariant("DataIns"))
        self.fModel.setHeaderData(ABBI, Qt.Horizontal, QVariant("Abbi"))
        self.fModel.setHeaderData(ANGRO, Qt.Horizontal, QVariant("Angro"))
        self.fModel.setHeaderData(DESC, Qt.Horizontal, QVariant("Desc"))
        self.fModel.setHeaderData(QT, Qt.Horizontal, QVariant("Qt"))
        self.fModel.setHeaderData(IMP, Qt.Horizontal, QVariant("Imp"))
        self.fModel.setHeaderData(EQUIV, Qt.Horizontal, QVariant("Equiv"))
        self.fModel.setHeaderData(MMID, Qt.Horizontal, QVariant("ScaffId"))
        self.fModel.setHeaderData(FATT, Qt.Horizontal, QVariant("Fatt"))
        self.fModel.setHeaderData(NOTE, Qt.Horizontal, QVariant("Note"))
        self.fModel.setSort(MMID, Qt.AscendingOrder)
        self.fModel.setRelation(MMID, QSqlRelation("magamaster",
                                            "id", "scaff"))
        self.fModel.select()
 def __init__(self, postgisDb, parent=None):
     """
     Constructor
     """
     super(ValidationHistory, self).__init__(parent)
     # Set up the user interface from Designer.
     # After setupUI you can access any designer object by doing
     # self.<objectname>, and you can use autoconnect slots - see
     # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
     # #widgets-and-dialogs-with-auto-connect
     self.setupUi(self)
     self.postgisDb = postgisDb
     self.dbEncoding = 'utf-8'
     self.dictNoUser = {
         'No User':
         self.tr("Select a username..."),  # no user name is selected
         'Error':
         self.tr("Processes with no user set"
                 ),  # "username" for processes unable to retrieve db user
         'User Name Error':
         self.tr("Unable to get database username."
                 )  # log message raised on username retrieving error
     }  # text used as indicator of userName box contents
     try:
         self.projectModel = QSqlTableModel(None, self.postgisDb.db)
         self.refreshViewTable(createTable=True)
     except Exception as e:
         QtGui.QMessageBox.critical(
             self, self.tr('Critical!'),
             self.
             tr('A problem occurred! Check log for details. (Did you select a database?)'
                ))
         QgsMessageLog.logMessage(': (did you choose )'.join(e.args),
                                  "DSG Tools Plugin",
                                  QgsMessageLog.CRITICAL)
Ejemplo n.º 3
0
    def setup_mcl_model_and_mapper(self, mcl_ref):
        """
        Load the data for the MCL portion of the form
        :param mcl_ref: str mcl_ref
        :return:
        """
        # Set up model
        self.mcl_model = QSqlTableModel(db=self.db)
        self.mcl_model.setTable('mcl')
        self.mcl_model.setFilter("mcl_ref = {}".format(int(mcl_ref)))
        self.mcl_model.select()
        if self.mcl_model.rowCount() != 1:
            msg = "MCL query for mcl_ref = {} returned {} rows".format(
                mcl_ref, self.mcl_model.rowCount())
            raise rn_except.RdpolyFormBadMclRefError(msg)

        # Set up mcl_mapper
        self.mcl_mapper = QDataWidgetMapper()
        self.mcl_mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
        self.mcl_mapper.setModel(self.mcl_model)
        self.mcl_mapper.addMapping(self.dlg.ui.mclLineEdit, MCL_REF)
        self.mcl_mapper.addMapping(self.dlg.ui.usrnLineEdit, USRN)
        self.mcl_mapper.addMapping(self.dlg.ui.lorDescPlainTextEdit, LOR_DESC)
        self.mcl_mapper.addMapping(self.dlg.ui.laneNumberLineEdit, LANE_NUMBER)
        self.mcl_mapper.addMapping(self.dlg.ui.speedLineEdit, SPEED_LIMIT)
        self.mcl_mapper.toFirst()
Ejemplo n.º 4
0
    def setup_model_and_mapper(self, mcl_ref):
        """
        Load the table data for selected record into a model and map to widgets.
        """
        # Set up model
        self.model = QSqlTableModel(db=self.db)
        self.model.setTable('mcl')
        self.model.setFilter("mcl_ref = {}".format(int(mcl_ref)))
        self.model.select()
        if self.model.rowCount() != 1:
            msg = "MCL query for mcl_ref = {} returned {} rows".format(
                mcl_ref, self.model.rowCount())
            raise rn_except.MclFormBadMclRefError(msg)

        # Set up mapper
        self.mapper = QDataWidgetMapper()
        self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
        self.mapper.setModel(self.model)
        self.mapper.addMapping(self.dlg.ui.mclLineEdit, MCL_REF)
        self.mapper.addMapping(self.dlg.ui.usrnLineEdit, USRN)
        self.mapper.addMapping(self.dlg.ui.streetClassComboBox, STREET_CLASS)
        self.mapper.addMapping(self.dlg.ui.ref1LineEdit, LOR_REF_1)
        self.mapper.addMapping(self.dlg.ui.ref2LineEdit, LOR_REF_2)
        self.mapper.addMapping(self.dlg.ui.laneNumberComboBox, LANE_NUMBER)
        self.mapper.addMapping(self.dlg.ui.carriagewayComboBox, CARRIAGEWAY)
        self.mapper.addMapping(self.dlg.ui.ruralUrbanComboBox, RURAL_URBAN_ID)
        self.mapper.addMapping(self.dlg.ui.speedLimitComboBox, SPEED_LIMIT)
        self.mapper.addMapping(self.dlg.ui.sectionTypeComboBox, SECTION_TYPE)
        self.mapper.addMapping(self.dlg.ui.sectionDescriptionPlainTextEdit,
                               LOR_DESC)
        self.mapper.setItemDelegate(MclEditorDelegate(self.dlg))
        self.mapper.toFirst()
Ejemplo n.º 5
0
    def fill_table_psector(self, widget, table_name, column_id):
        """ Set a model with selected filter.
        Attach that model to selected table """

        # Set model
        self.model = QSqlTableModel()
        self.model.setTable(self.schema_name + "." + table_name)
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.model.setSort(0, 0)
        self.model.select()

        # Check for errors
        if self.model.lastError().isValid():
            self.controller.show_warning(self.model.lastError().text())
        # Attach model to table view
        widget.setModel(self.model)
        # put combobox in qtableview
        sql = "SELECT * FROM " + self.schema_name + "." + table_name + " ORDER BY " + column_id
        rows = self.controller.get_rows(sql)
        for x in range(len(rows)):
            combo = QComboBox()
            sql = "SELECT DISTINCT(priority) FROM " + self.schema_name + "." + table_name
            row = self.controller.get_rows(sql)
            utils_giswater.fillComboBox(combo, row, False)
            row = rows[x]
            priority = row[4]
            utils_giswater.setSelectedItem(combo, str(priority))
            i = widget.model().index(x, 4)
            widget.setIndexWidget(i, combo)
            #combo.setStyleSheet("background:#F2F2F2")
            combo.setStyleSheet("background:#E6E6E6")
            combo.currentIndexChanged.connect(
                partial(self.update_combobox_values, widget, combo, x))
Ejemplo n.º 6
0
 def __init__(self, domainDict, parent=None, db=QSqlDatabase):
     """
     Constructor
     """
     QSqlTableModel.__init__(self, parent=parent, db=db)
     self.dict = domainDict
     self.db = db
Ejemplo n.º 7
0
 def __init__(self, domainDict, parent=None, db=QSqlDatabase):
     """
     Constructor
     """
     QSqlTableModel.__init__(self, parent=parent, db=db)
     self.dict = domainDict
     self.db = db
Ejemplo n.º 8
0
 def updateDbLineEdit(self):
     """
     Updates the database information
     """
     database = ''
     try:
         self.configWindow.widget.abstractDb.checkAndOpenDb()
         database = self.configWindow.widget.comboBoxPostgis.currentText()
         self.databaseLineEdit.setText(database)
         self.validationManager = ValidationManager(
             self.configWindow.widget.abstractDb, self.iface)
         self.populateProcessList()
         self.databaseLineEdit.setText(database)
         # adjusting flags table model
         self.projectModel = QSqlTableModel(
             None, self.configWindow.widget.abstractDb.db)
         self.projectModel.setTable('validation.aux_flags_validacao')
         self.projectModel.select()
         self.tableView.setModel(self.projectModel)
     except Exception as e:
         QtGui.QMessageBox.critical(
             self, self.tr('Critical!'),
             self.tr('A problem occurred! Check log for details.'))
         QgsMessageLog.logMessage(
             self.tr('Error loading db: ') + ':'.join(e.args),
             "DSG Tools Plugin", QgsMessageLog.CRITICAL)
         self.processTreeWidget.clear()
Ejemplo n.º 9
0
    def __init__(self):
        super(MainForm, self).__init__()

        self.model = QSqlTableModel(self)
        self.model.setTable('tbl_symbols')
        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        addButton = QPushButton("&Add")
        deleteButton = QPushButton("&Delete")

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(deleteButton)
        buttonLayout.addStretch()

        lay = QHBoxLayout()
        lay.addWidget(self.view)
        lay.addLayout(buttonLayout)
        self.setLayout(lay)

        self.connect(addButton, SIGNAL("clicked()"), self.addRecord)
        self.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)
Ejemplo n.º 10
0
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()

        column = index.column()
        if role == Qt.DisplayRole:
            if column == DATAINS:
                return QVariant(QSqlTableModel.data(self,
                            index).toDate().toString(DATEFORMAT))
            if column == IMP:
                return QVariant("€ %s" %
                        QSqlTableModel.data(self, index).toString())


        if role == Qt.TextAlignmentRole:
            if column == DATAINS:
                return QVariant(int(Qt.AlignLeft|Qt.AlignVCenter))
            else:
                return QVariant(int(Qt.AlignRight|Qt.AlignVCenter))


        if role == Qt.BackgroundRole:
            if column == QT:
                if QSqlTableModel.data(self, index).toInt()[0] == 0:
                    return QVariant(QColor(Qt.red))

        # default, no specific condition found
        return QSqlTableModel.data(self, index, role)
Ejemplo n.º 11
0
    def setup_rdpoly_model_and_mapper(self, rd_pol_id):
        """
        Load the data for the Polygon portion of the form
        :param rd_pol_id: str rd_pol_id
        :return:
        """
        # Set up model
        self.rdpoly_model = QSqlTableModel(db=self.db)
        self.rdpoly_model.setTable('rdpoly')
        self.rdpoly_model.setFilter("rd_pol_id = {}".format(int(rd_pol_id)))
        self.rdpoly_model.select()
        if self.rdpoly_model.rowCount() != 1:
            msg = "Table rdpoly query for rd_pol_id = {} returned {} rows".format(
                rd_pol_id, self.rdpoly_model.rowCount())
            raise rn_except.RdpolyFormBadRdpolyRefError(msg)

        # Set up rdpoly_mapper
        self.rdpoly_mapper = QDataWidgetMapper()
        self.rdpoly_mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
        self.rdpoly_mapper.setModel(self.rdpoly_model)
        self.rdpoly_mapper.addMapping(self.dlg.ui.rdpolyLineEdit, RD_POL_ID)
        self.rdpoly_mapper.addMapping(self.dlg.ui.numberLineEdit, DESC_3)
        self.rdpoly_mapper.addMapping(self.dlg.ui.elementComboBox, ELEMENT)
        self.rdpoly_mapper.addMapping(self.dlg.ui.hierarchyComboBox, HIERARCHY)
        self.rdpoly_mapper.addMapping(self.dlg.ui.offsetComboBox, OFFSET)
        self.rdpoly_mapper.setItemDelegate(RdpolyEditorDelegate(self.dlg))
        self.rdpoly_mapper.toFirst()
Ejemplo n.º 12
0
    def __init__(self, parent):
        # type: (object) -> object
        QSqlTableModel.__init__(self, parent)

        self.setTable("Register")

        self.select()

        self.setEditStrategy(QSqlTableModel.OnManualSubmit)
Ejemplo n.º 13
0
    def __init__(self):
        super(MainWindow, self).__init__(None)
        uic.loadUi("mainwindow.ui", self)

        self.model = QSqlTableModel(self)
        self.model.setTable("student")
        self.model.select()
        # 设置编辑策略
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.tableView.setModel(self.model)
Ejemplo n.º 14
0
 def create_data_model(self, table_id):
     """
     create an object from the QSqlTableModel class used to data modifications
     to send to the database
     :param table_id: the id passed from the radio button
     :return: void
     """
     self.data_model = QSqlTableModel(db=self.db)
     self.data_model.setTable(self.tables[table_id])
     self.data_model.setEditStrategy(QSqlTableModel.OnManualSubmit)
     self.data_model.setSort(2, Qt.AscendingOrder)
     self.data_model.select()
     while self.data_model.canFetchMore():
         self.data_model.fetchMore()
Ejemplo n.º 15
0
    def set_table_model(self, table_object, geom_type, expr_filter):
        """ Sets a TableModel to @widget_name attached to
            @table_name and filter @expr_filter 
        """

        expr = None
        if expr_filter:
            # Check expression
            (is_valid,
             expr) = self.check_expression(expr_filter)  #@UnusedVariable
            if not is_valid:
                return expr

        # Set a model with selected filter expression
        table_name = "v_edit_" + geom_type
        if self.schema_name not in table_name:
            table_name = self.schema_name + "." + table_name

        # Set the model
        model = QSqlTableModel()
        model.setTable(table_name)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        model.select()
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())
            return expr

        # Attach model to selected widget
        if type(table_object) is str:
            widget = utils_giswater.getWidget(table_object)
            if not widget:
                message = "Widget not found"
                self.controller.log_info(message, parameter=table_object)
                return expr
        elif type(table_object) is QTableView:
            widget = table_object
        else:
            message = "Table_object is not a table name or QTableView"
            self.controller.log_info(message)
            return expr

        if expr_filter:
            widget.setModel(model)
            widget.model().setFilter(expr_filter)
            widget.model().select()
        else:
            widget.setModel(None)

        return expr
Ejemplo n.º 16
0
    def fill_table_config(self, widget, table_name):
        """ Set a model with selected filter. Attach that model to selected table """

        # Set model
        model = QSqlTableModel()
        model.setTable(table_name)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        model.select()

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())

        # Attach model to table view
        widget.setModel(model)
Ejemplo n.º 17
0
 def populate_list(self, table_id):
     """
     populate the list view on initialisation and when radio buttons are toggled
     :param table_id: the id passed from the radio button
     :return: void
     """
     self.lsg_lu_dia.ui.addLookupLineEdit.clear()
     self.items_model = QSqlTableModel(db=self.db)
     self.items_model.setTable(self.tables[table_id])
     self.items_model.setEditStrategy(QSqlTableModel.OnManualSubmit)
     self.items_model.setSort(2, Qt.AscendingOrder)
     self.items_model.select()
     while self.items_model.canFetchMore():
         self.items_model.fetchMore()
     self.lsg_lu_dia.ui.itemsListView.setModel(self.items_model)
     self.lsg_lu_dia.ui.itemsListView.setModelColumn(2)
Ejemplo n.º 18
0
 def setData(self, index, value, role=Qt.EditRole):
     """
     Custom reimplementation of the method setData.
     It is necessary to work with value map and value relation.
     index: column index to be set
     value: value to be set
     role: role used
     """
     column = self.headerData(index.column(), Qt.Horizontal)
     newValue = value
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             newValue = int(valueMap[value])
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             code_names = value[1:-1].split(',')
             codes = []
             for code_name in code_names:
                 code = valueMap[code_name]
                 codes.append(code)
             if len(codes) > 0:
                 newValue = '{%s}' % ','.join(map(str, codes))
     return QSqlTableModel.setData(self, index, newValue, role)
Ejemplo n.º 19
0
 def setData(self, index, value, role=Qt.EditRole):
     column = self.headerData(index.column(), Qt.Horizontal)
     newValue = value
     if self.dict.has_key(column):
         dict = self.dict[column]
         newValue = int(dict[value])
     return QSqlTableModel.setData(self, index, newValue, role)
Ejemplo n.º 20
0
    def __init__(self, header=None, db=None, parent=None):
        super(FilterDialog, self).__init__(parent)

        self.setupUi(self)

        self.dbi = ""
        if not db:
            filename = ":memory:"
            self.dbi = QSqlDatabase.addDatabase("QSQLITE")
            self.dbi.setDatabaseName(filename)
            self.dbi.open()

        self.creaStrutturaDB(header)

        self.sModel = QSqlTableModel(self)
        self.sModel.setTable(QString("filtertable"))
        self.sModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.sModel.select()

        self.filterTableView.setModel(self.sModel)
        self.filterTableView.setColumnHidden(0, True)
        self.filterTableView.setAlternatingRowColors(True)

        self.connect(self.sModel, SIGNAL("primeInsert (int,QSqlRecord&)"),
                self.updRows)
        self.connect(self.addFilterPushButton, SIGNAL("clicked()"),
                self.accept)
        self.connect(self.addLinePushButton, SIGNAL("clicked()"),
                self.addLine)

        self.sModel.insertRows(0, 10)
        self.sModel.submitAll()
        self.restoreSettings()
        self.resultFilter = None
    def __init__(self):
        super(MainForm, self).__init__()
        
        self.model = QSqlTableModel(self)
        self.model.setTable('tbl_symbols')
        self.model.select()
        
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        addButton = QPushButton("&Add")
        deleteButton = QPushButton("&Delete")
        
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(deleteButton)
        buttonLayout.addStretch()
        
        lay = QHBoxLayout()
        lay.addWidget(self.view)
        lay.addLayout(buttonLayout)
        self.setLayout(lay)
        
        self.connect(addButton, SIGNAL("clicked()"), self.addRecord)
        self.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)
Ejemplo n.º 22
0
 def __init__(self, postgisDb, parent=None):
     """
     Constructor
     """
     super(ValidationHistory, self).__init__(parent)
     # Set up the user interface from Designer.
     # After setupUI you can access any designer object by doing
     # self.<objectname>, and you can use autoconnect slots - see
     # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
     # #widgets-and-dialogs-with-auto-connect
     self.setupUi(self)
     self.postgisDb = postgisDb
     self.projectModel = QSqlTableModel(None, self.postgisDb.db)
     self.projectModel.setTable('validation.process_history')
     self.projectModel.select()
     self.tableView.setModel(self.projectModel)
Ejemplo n.º 23
0
 def get_color_by_option(self, index):
     option = QSqlTableModel.data(self, self.index(index.row(), 3)).toString()
     if option == 'left':
         return QColor(Qt.darkGreen)
     if option == 'right':
         return QColor(Qt.darkCyan)
     return QVariant()
Ejemplo n.º 24
0
 def data(self, index, role):
     """
     Custom reimplementation of the method data.
     It is necessary to work with value map and value relation.
     index: column index
     role: role used to get the data
     """
     dbdata = QSqlTableModel.data(self, index, role)
     column = self.headerData(index.column(), Qt.Horizontal)
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             if str(dbdata) in valueMap.values():
                 id = valueMap.values().index(str(dbdata))
                 return valueMap.keys()[id]
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             codes = str(dbdata)[1:-1].split(',')
             code_names = list()
             for c in codes:
                 if str(c) in valueMap.values():
                     id = valueMap.values().index(str(c))
                     code_name = valueMap.keys()[id]
                     code_names.append(code_name)
             if len(code_names) > 0:
                 return '{%s}' % ','.join(code_names)
     return dbdata
Ejemplo n.º 25
0
 def setData(self, index, value, role=Qt.EditRole):
     """
     Custom reimplementation of the method setData.
     It is necessary to work with value map and value relation.
     index: column index to be set
     value: value to be set
     role: role used
     """
     column = self.headerData(index.column(), Qt.Horizontal)
     newValue = value
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             newValue = int(valueMap[value])
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             code_names = value[1:-1].split(',')
             codes = []
             for code_name in code_names:
                 code = valueMap[code_name]
                 codes.append(code)
             if len(codes) > 0:
                 newValue = '{%s}' % ','.join(map(str, codes))
     return QSqlTableModel.setData(self, index, newValue, role)
Ejemplo n.º 26
0
 def data(self, index, role):
     """
     Custom reimplementation of the method data.
     It is necessary to work with value map and value relation.
     index: column index
     role: role used to get the data
     """
     dbdata = QSqlTableModel.data(self, index, role)
     column = self.headerData(index.column(), Qt.Horizontal)
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             if str(dbdata) in valueMap.values():
                 id = valueMap.values().index(str(dbdata))
                 return valueMap.keys()[id]
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             codes = str(dbdata)[1:-1].split(',')
             code_names = list()
             for c in codes:
                 if str(c) in valueMap.values():
                     id = valueMap.values().index(str(c))
                     code_name = valueMap.keys()[id]
                     code_names.append(code_name)
             if len(code_names) > 0:
                 return '{%s}' % ','.join(code_names)
     return dbdata
Ejemplo n.º 27
0
    def __init__(self, parent):
        QDialog.__init__(self)
        self.parent = parent
        self.model = QSqlTableModel(self, DBHandle.default)
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.model.setTable("player")
        self.model.setSort(1, 0)
        self.model.setHeaderData(1, Qt.Horizontal, QVariant(m18nc("Player", "Name")))
        self.model.setFilter('name not like "ROBOT %" and name not like "Robot %"')
        self.view = MJTableView(self)
        self.view.verticalHeader().show()
        self.view.setModel(self.model)
        self.view.hideColumn(0)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.newButton = self.buttonBox.addButton(m18nc('define a new player', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.slotInsert)
        self.deleteButton = self.buttonBox.addButton(m18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(self.buttonBox)
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

        self.setWindowTitle(m18n("Players") + ' - Kajongg')
        self.setObjectName('Players')
Ejemplo n.º 28
0
 def data(self, index, role):
     code = QSqlTableModel.data(self, index, role)
     column = self.headerData(index.column(), Qt.Horizontal)
     if self.dict.has_key(column):
         dict = self.dict[column]
         if str(code) in dict.values():
             id = dict.values().index(str(code))
             return dict.keys()[id]
     return code
Ejemplo n.º 29
0
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()

        column = index.column()
        if role == Qt.DisplayRole:
            if column == SIMP:
                return QVariant("€ %.2f" %
                        QSqlTableModel.data(self, index).toDouble()[0])
            elif column == SIVA:
                return QVariant("%.2f %%" %
                        QSqlTableModel.data(self, index).toDouble()[0])

        if role == Qt.TextAlignmentRole:
            return QVariant(int(Qt.AlignRight|Qt.AlignVCenter))

        # default, no specific condition found
        return QSqlTableModel.data(self, index, role)
Ejemplo n.º 30
0
    def get_table_model(table, table_filters=None):
        """Get table model of table.

        :param table: Table target be inserted
        :type table: str

        :return: Table Model for contact
        :rtype: QSqlTableModel
        """
        CadastaDatabase.open_database()
        table_model = QSqlTableModel()
        table_model.setTable(table)
        table_model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        if table_filters:
            for table_filter in table_filters:
                table_model.setFilter(table_filter)
        table_model.select()
        return table_model
Ejemplo n.º 31
0
    def data(self, index, role):
        if role == Qt.FontRole:
            return self.font

        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter

        if role == Qt.BackgroundColorRole:
            return self.get_color_by_option(index)

        if index.column() == 2:
            value = QSqlTableModel.data(self, index, Qt.EditRole).toInt()[0] == 1
            if role == Qt.CheckStateRole:
                return Qt.Checked if value else Qt.Unchecked
            if role == Qt.EditRole or role == Qt.DisplayRole:
                return QVariant(value)
            return QVariant()
        return QSqlTableModel.data(self, index, role)
Ejemplo n.º 32
0
    def create_widgets(self):
        self.model = QSqlTableModel(self)
        self.model.setTable("employee")
        self.model.setSort(ID, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.model.setHeaderData(CITY, Qt.Horizontal,
                QVariant("City"))
        self.model.setHeaderData(DEPARTMENT, Qt.Horizontal,
                QVariant("Department"))
        self.model.setHeaderData(FIRSTNAME, Qt.Horizontal,
                QVariant("First Name"))
        self.model.setHeaderData(LASTNAME, Qt.Horizontal,
                QVariant("Last Name"))
        self.model.setHeaderData(SEX, Qt.Horizontal,
                QVariant("sex"))
        self.model.setHeaderData(ADDRESS, Qt.Horizontal,
                QVariant("Address"))
        self.model.setHeaderData(PID, Qt.Horizontal,
                QVariant("PID"))
        
        self.model.setHeaderData(TITLE, Qt.Horizontal,
                QVariant("Title"))
        
        self.model.setHeaderData(SOLARY, Qt.Horizontal,
                QVariant("SOLARY"))
        self.model.setHeaderData(SHIFT, Qt.Horizontal,
                QVariant("SHIFT"))
        self.model.setHeaderData(HOURS, Qt.Horizontal,
                QVariant("HOURS"))
        
        self.model.select()
    

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.buttonBox = QDialogButtonBox()
        self.addButton = self.buttonBox.addButton(u"&Добавить",
                QDialogButtonBox.ActionRole)
        self.deleteButton = self.buttonBox.addButton(u"&Удалить",
                QDialogButtonBox.ActionRole)
        self.sortButton = self.buttonBox.addButton(u"&Сортировать",
                QDialogButtonBox.ActionRole)
        

        menu = QMenu(self)
        self.sortByTitleAction = menu.addAction(u"Сортировка по &Title")
        self.sortBySolaryAction = menu.addAction(
                u"Сортировка по &SOLARY")
        self.sortByIDAction = menu.addAction(u"Сортировка по &ID")
        self.sortButton.setMenu(menu)
        self.closeButton = self.buttonBox.addButton(QDialogButtonBox.Close)
Ejemplo n.º 33
0
    def fill_table(self,
                   widget,
                   table_name,
                   set_edit_strategy=QSqlTableModel.OnManualSubmit):
        """ Set a model with selected filter.
        Attach that model to selected table """

        # Set model
        self.model = QSqlTableModel()
        self.model.setTable(self.schema_name + "." + table_name)
        self.model.setEditStrategy(set_edit_strategy)
        self.model.setSort(0, 0)
        self.model.select()

        # Check for errors
        if self.model.lastError().isValid():
            self.controller.show_warning(self.model.lastError().text())
        # Attach model to table view
        widget.setModel(self.model)
Ejemplo n.º 34
0
    def __init__(self, parent=None):
        super(EditItemDlg, self).__init__(parent)
        #     # Create model
        self.locusTypeModel = QSqlTableModel(self)
        self.locusTypeModel.setTable("tbl_locusType")
        self.locusTypeModel.select()

        # Create combo and set its model
        self.locusTypeComboBox = self.createCombobox(self.locusTypeModel,
                                                     "LABEL")
        typeLabel = QLabel("&Type:")
        typeLabel.setBuddy(self.locusTypeComboBox)

        #     # Create model
        self.locusSubTypeModel = QSqlTableModel(self)
        self.locusSubTypeModel.setTable("tbl_locus_subType1")
        #self.locusSubTypeModel.select()

        # Create combo and set its model
        self.locusSubTypeCombobox = self.createCombobox(
            self.locusSubTypeModel, "label")
        #
        # self.locusSubTypeCombobox = QComboBox()
        # self.locusSubTypeCombobox.setModel(self.locusSubTypeModel)
        # self.locusSubTypeCombobox.setModelColumn(
        #     self.locusTypeModel.fieldIndex("label"))

        #     # Create model
        # self.locusSubType2Model = QSqlTableModel(self)
        # self.locusSubType2Model.setTable("tbl_locus_subType1")
        # self.locusSubType2Model.select()

        controlLayout = QGridLayout()
        controlLayout.addWidget(self.locusTypeComboBox, 4, 0)
        controlLayout.addWidget(self.locusSubTypeCombobox, 5, 0)

        self.setLayout(controlLayout)
        self.resize(500, 125)

        self.locusTypeComboBox.currentIndexChanged.connect(self.f)
Ejemplo n.º 35
0
    def __init__(self, parent):
        QDialog.__init__(self)
        self.parent = parent
        self.model = QSqlTableModel(self, DBHandle.default)
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.model.setTable("player")
        self.model.setSort(1, 0)
        self.model.setHeaderData(1, Qt.Horizontal,
                                 QVariant(m18nc("Player", "Name")))
        self.model.setFilter(
            'name not like "ROBOT %" and name not like "Robot %"')
        self.view = MJTableView(self)
        self.view.verticalHeader().show()
        self.view.setModel(self.model)
        self.view.hideColumn(0)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.newButton = self.buttonBox.addButton(
            m18nc('define a new player', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.slotInsert)
        self.deleteButton = self.buttonBox.addButton(
            m18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(self.buttonBox)
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

        self.setWindowTitle(m18n("Players") + ' - Kajongg')
        self.setObjectName('Players')
Ejemplo n.º 36
0
    def __init__(self, name, table, parent=None):
        super(DataDialog, self).__init__(parent)

        self.name = name

        self.resize(600, 300)

        self.model = QSqlTableModel(self)
        self.model.setTable(table)
        self.model.setSort(ID, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant(_("Id")))
        self.model.setHeaderData(EMAIL, Qt.Horizontal, QVariant(_("Email")))
        self.model.setHeaderData(WWW, Qt.Horizontal, QVariant(_("WWW")))
        self.model.setHeaderData(PACKAGE, Qt.Horizontal, QVariant(_("Package")))
        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        # self.view.setColumnHidden(ID, True)
        # self.view.resizeColumnsToContents()

        addButton = QPushButton(_("&Add"))
        addButton.setIcon(QIcon(":/add.png"))
        deleteButton = QPushButton(_("&Delete"))
        deleteButton.setIcon(QIcon(":/delete.png"))
        okButton = QPushButton(_("&OK"))
        okButton.setIcon(QIcon(":/quit.png"))

        addButton.setFocusPolicy(Qt.NoFocus)
        deleteButton.setFocusPolicy(Qt.NoFocus)

        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(deleteButton)
        buttonLayout.addStretch()
        buttonLayout.addWidget(okButton)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)

        self.connect(addButton, SIGNAL("clicked()"), self.addRecord)
        self.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)
        self.connect(okButton, SIGNAL("clicked()"), self.accept)

        self.setWindowTitle(name)
Ejemplo n.º 37
0
    def data(self, QModelIndex, role):

        if role == QtCore.Qt.BackgroundRole:
            # if QModelIndex.row() in [1, 3]:
            #     return QtGui.QBrush(QtCore.Qt.yellow)
            # else:
            #     return QtGui.QBrush(QtCore.Qt.red)

            value = QModelIndex.data()
            print(value)
            print(type(value))
            if value in ('2020', '135'):
                return QtGui.QBrush(QtCore.Qt.yellow)
            else:
                return QtGui.QBrush(QtCore.Qt.red)
        return QSqlTableModel.data(self, QModelIndex, role)
Ejemplo n.º 38
0
 def __init__(self):
     self.logfile = open('logfile')
     self.db = QSqlDatabase.addDatabase("QSQLITE")
     self.db.setDatabaseName('sfile.db')
     self.db.open()
     self.projectModel_blocked = QSqlTableModel()
     self.projectModel_blacklist = QSqlTableModel()
     self.projectModel_mac = QSqlTableModel()
     self.sniff = Sniffer()
     self.sniff.start_gui()
     self.fnotification = share.get_flags()['notification']
 def showTable(self, table):
     """
     Public slot to show the contents of a table.
     
     @param table name of the table to be shown (string or QString)
     """
     model = QSqlTableModel(self.table, self.connections.currentDatabase())
     model.setEditStrategy(QSqlTableModel.OnRowChange)
     model.setTable(table)
     model.select()
     if model.lastError().type() != QSqlError.NoError:
         self.emit(SIGNAL("statusMessage(QString)"), model.lastError().text())
     self.table.setModel(model)
     self.table.setEditTriggers(
         QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed)
     
     self.table.resizeColumnsToContents()
     
     self.connect(self.table.selectionModel(), 
                  SIGNAL("currentRowChanged(QModelIndex, QModelIndex)"), 
                  self.updateActions)
     
     self.updateActions()
Ejemplo n.º 40
0
 def setData(self, index, value, role=Qt.EditRole):
     column = self.headerData(index.column(), Qt.Horizontal)
     newValue = value
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             newValue = int(valueMap[value])
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             code_names = value[1:-1].split(',')
             codes = []
             for code_name in code_names:
                 code = valueMap[code_name]
                 codes.append(code)
             if len(codes) > 0:
                 newValue = '{%s}' % ','.join(map(str, codes))
     return QSqlTableModel.setData(self, index, newValue, role)
Ejemplo n.º 41
0
 def setData(self, index, value, role=Qt.EditRole):
     column = self.headerData(index.column(), Qt.Horizontal)
     newValue = value
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             newValue = int(valueMap[value])
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             code_names = value[1:-1].split(',')
             codes = []
             for code_name in code_names:
                 code = valueMap[code_name]
                 codes.append(code)
             if len(codes) > 0:
                 newValue = '{%s}' % ','.join(map(str, codes))
     return QSqlTableModel.setData(self, index, newValue, role)
Ejemplo n.º 42
0
 def setupModels(self):
     """
         Initialize all the application models
     """
     # setup clientiModel
     self.cModel = QSqlTableModel(self)
     self.cModel.setTable(QString("clienti"))
     self.cModel.setHeaderData(CID, Qt.Horizontal, QVariant("ID"))
     self.cModel.setHeaderData(CRAGSOC, Qt.Horizontal, QVariant("RagSoc"))
     self.cModel.setHeaderData(CIND, Qt.Horizontal, QVariant("Indirizzo"))
     self.cModel.setHeaderData(CPIVA, Qt.Horizontal, QVariant("PIva"))
     self.cModel.setHeaderData(CCF, Qt.Horizontal, QVariant("CF"))
     self.cModel.setHeaderData(CTEL, Qt.Horizontal, QVariant("Tel"))
     self.cModel.setHeaderData(CFAX, Qt.Horizontal, QVariant("Fax"))
     self.cModel.setHeaderData(CCELL, Qt.Horizontal, QVariant("Cell"))
     self.cModel.setHeaderData(CEMAIL, Qt.Horizontal, QVariant("Email"))
     self.cModel.setHeaderData(CNOTE, Qt.Horizontal, QVariant("Note"))
     self.cModel.select()
Ejemplo n.º 43
0
    def create_widgets(self, table):
        self.model = QSqlTableModel(self)
        self.model.setTable(table)
        self.model.setSort(NAME, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.model.setHeaderData(NAME, Qt.Horizontal, QVariant("Name"))
        self.model.setHeaderData(DESCRIPTION, Qt.Horizontal,
                                 QVariant("Description"))
        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.addButton = QPushButton("&Add")
        self.deleteButton = QPushButton("&Delete")
        self.okButton = QPushButton("&OK")
Ejemplo n.º 44
0
    def setupModels(self):
        """
            Initialize all the application models
        """
        # setup slaveModel
        self.sModel = QSqlTableModel(self)
        self.sModel.setTable(QString("ddtslave"))
        self.sModel.setHeaderData(SID, Qt.Horizontal, QVariant("ID"))
        self.sModel.setHeaderData(SQT, Qt.Horizontal, QVariant("Qt"))
        self.sModel.setHeaderData(SDESC, Qt.Horizontal, QVariant("Descrizione"))
        self.sModel.setHeaderData(SMID, Qt.Horizontal, QVariant("idlegato"))
        self.sModel.setEditStrategy(QSqlTableModel.OnRowChange)
        self.sModel.select()

        # setup masterModel
        self.mModel = QSqlRelationalTableModel(self)
        self.mModel.setTable(QString("ddtmaster"))
        self.mModel.setSort(MDATA, Qt.AscendingOrder)
        self.mModel.setRelation(MIDCLI, QSqlRelation("clienti",
                                            "id", "ragsoc"))
        self.mModel.select()
Ejemplo n.º 45
0
 def data(self, index, role):
     dbdata = QSqlTableModel.data(self, index, role)
     column = self.headerData(index.column(), Qt.Horizontal)
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             if str(dbdata) in valueMap.values():
                 id = valueMap.values().index(str(dbdata))
                 return valueMap.keys()[id]
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             codes = str(dbdata)[1:-1].split(',')
             code_names = list()
             for c in codes:
                 if str(c) in valueMap.values():
                     id = valueMap.values().index(str(c))
                     code_name = valueMap.keys()[id]
                     code_names.append(code_name)
             if len(code_names) > 0:
                 return '{%s}' % ','.join(code_names)
     return dbdata
Ejemplo n.º 46
0
 def data(self, index, role):
     dbdata = QSqlTableModel.data(self, index, role)
     column = self.headerData(index.column(), Qt.Horizontal)
     if self.dict.has_key(column):
         if isinstance(self.dict[column], dict):
             valueMap = self.dict[column]
             if str(dbdata) in valueMap.values():
                 id = valueMap.values().index(str(dbdata))
                 return valueMap.keys()[id]
         elif isinstance(self.dict[column], tuple):
             tupla = self.dict[column]
             valueMap = self.makeValueRelationDict(tupla[0], tupla[1])
             codes = str(dbdata)[1:-1].split(',')
             code_names = list()
             for c in codes:
                 if str(c) in valueMap.values():
                     id = valueMap.values().index(str(c))
                     code_name = valueMap.keys()[id]
                     code_names.append(code_name)
             if len(code_names) > 0:
                 return '{%s}' % ','.join(code_names)
     return dbdata
Ejemplo n.º 47
0
class QuestionDlg(QDialog):
    def __init__(self, parent=None):
        super(QuestionDlg,self).__init__(parent)
        # self.setStyleSheet("background-image:url('image/panelbg.jpg'); border: 2px; border-radius 2px;")
        # self.createDb()
        # return

        self.db = QSqlDatabase.addDatabase("QSQLITE");  
        self.db.setDatabaseName("studentNew.db")
        if not self.db.open():
            QMessageBox.warning(None, "错误",  "数据库连接失败: %s" % self.db.lastError().text())
            sys.exit(1)

        self.g_curClassName = ""
        self.deleteTmpdata()

        self.setWindowFlags(Qt.CustomizeWindowHint)
        # self.setStyleSheet("border: 2px; border-radius 2px;")
        # self.setWindowFlags(Qt.FramelessWindowHint)
        self.setStyleSheet("background-color: rgba(132, 171, 208, 200);")

        self.tabWidget=QTabWidget(self)
        self.tabWidget.currentChanged.connect(self.changeTab)
        # tabWidget.setTabShape(QTabWidget.Triangular)
        self.tabWidget.setStyleSheet("QTabWidget::pane{border-width:1px;border-color:rgb(48, 104, 151);\
            border-style: outset;background-color: rgb(132, 171, 208);\
            background: transparent;} \
            QTabWidget::tab-bar{border-width:0px;}\
            QTabBar::tab { height: 60px; width: 260px; color:rgb(0, 0, 255); font-size:20px; font-weight:bold;} \
            QTabBar::tab:hover{background:rgb(255,255, 255, 100);} \
            QTabBar::tab:selected{border-color:green;background-color:white;color:green;}")
        # tabWidget.setStyleSheet("QTabBar::tab:hover{background:rgb(255,255, 255, 100);}")
        self.btngroup = QButtonGroup()
        self.popMenu = QMenu(self)
        entry1 = self.popMenu.addAction("正确")
        self.connect(entry1,SIGNAL('triggered()'), lambda : self.answerRight())
        entry2 = self.popMenu.addAction("错误")
        self.connect(entry2,SIGNAL('triggered()'), lambda : self.answerWrong())
        entry3 = self.popMenu.addAction("替换")
        self.connect(entry3,SIGNAL('triggered()'), lambda : self.resetStudent())

        # Create the first tab page.
        self.w1=QWidget()
        self.w1.setAccessibleName("w1tab")
        self.genOneTab()
        
        # Create the second tab page.
        self.w2=QWidget()
        self.w2.setAccessibleName("w2tab")        
        self.genTwoTab()

        self.tabWidget.addTab(self.w1,"")
        self.tabWidget.addTab(self.w2,"班级学生信息管理")
        self.tabWidget.resize(940,700)

        btnclose = QPushButton(self)
        btnclose.setToolTip("关闭")
        btnclose.setText("╳")
        btnclose.setGeometry(915, 5, 20, 20)
        btnclose.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255)")
        btnclose.clicked.connect(self.close)
        btnMinimized = QPushButton(self)
        btnMinimized.setToolTip("最小化")
        btnMinimized.setText("▁")
        btnMinimized.setGeometry(890, 5, 20, 20)
        btnMinimized.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255)")
        btnMinimized.clicked.connect(lambda: self.showMinimized())
        self.btnSysMenu = QPushButton(self)
        # self.btnSysMenu.setText("▼")
        self.btnSysMenu.setGeometry(865, 5, 20, 20)
        self.btnSysMenu.setToolTip("系统设置")
        self.btnSysMenu.clicked.connect(lambda: self.showMinimized())
        menufont = QFont("宋体", 10)
        popMenu = QMenu(self)
        entry1 = popMenu.addAction("所有学生提问信息清零")
        entry1.setFont(menufont)
        self.connect(entry1,SIGNAL('triggered()'), self.initStudent)
        entry2 = popMenu.addAction("清除本堂课提问人员")
        entry2.setFont(menufont)
        self.connect(entry2,SIGNAL('triggered()'), self.deleteTmpdata)
        entry3 = popMenu.addAction("关于...")
        entry3.setFont(menufont)
        self.connect(entry3,SIGNAL('triggered()'), self.aboutMe)
        entry4 = popMenu.addAction("导出...")
        entry4.setFont(menufont)
        self.connect(entry4,SIGNAL('triggered()'), self.exportNotice)

        self.btnSysMenu.setMenu(popMenu)
        self.btnSysMenu.setStyleSheet("QPushButton::menu-indicator {image: url('image/sysmenu.png');subcontrol-position: right center;} ")
        # self.btnSysMenu.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255);")

        authorinfo = QLabel(self.tabWidget)
        # authorinfo.setToolTip("关闭")
        authorinfo.setText("程序设计:汕头市大华路第一小学 赵小娜,有任何问题请反馈至[email protected]。")
        authorinfo.setGeometry(20, 665, 470, 26)
        authorinfo.setFont(QFont('Courier New'))
        authorinfo.setStyleSheet("background-color:rgba(255, 255, 255,160); font-size:12px;border: 1px solid rgb(60,200,255,200);color:rgba(0,0,0,220);border-radius:12px;")

        self.setWindowTitle("课堂随机提问")
        self.setWindowIcon(QIcon("image/start.ico"))
        self.setGeometry(100, 20, 940, 700)

        # self.changeTab()

        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

        self.btn_start.setMyarg('start')
        
        # print(self.btn_start.getMyarg())

        self.connect(self.btn_start, SIGNAL("clicked()"), self.startChoice)
        # self.connect(self.w1title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
        # self.connect(self.btn_start2, SIGNAL("clicked()"), self.startChoice)
        # self.connect(self.w2title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
        self.btngroup.buttonClicked[int].connect(self.btns_click)
        # self.connect(self.btn_start,  SIGNAL("myslot(PyQt_PyObject)"), self.myslot)  
        # self.connect(self.btngroup, SIGNAL("buttonClicked(int)"), lambda:self.btns_click())

    def myslot(self, text):  
        # print(text, self.dict_choices)
        self.g_curbtn = text
        if self.g_curbtn not in self.dict_choices:
            self.btnSysMenu.setFocus()
            return

        # print(self.btngroup.button(int(self.g_curbtn)).parent())
        # print(type(self.btngroup.button(int(self.g_curbtn)).parentWidget()))
        pos = self.btngroup.button(int(self.g_curbtn)).parent().mapToGlobal(self.btngroup.button(int(self.g_curbtn)).pos())
        width = self.btngroup.button(int(self.g_curbtn)).rect().height()
        # print("-----", pos, width)
        pos.setY(pos.y()+width-5)

        indx = 0
        for istate in self.dict_choices[self.g_curbtn]:
            if istate == '1':
                self.popMenu.actions()[indx].setEnabled(True)
            elif istate == '0':
                self.popMenu.actions()[indx].setEnabled(False)
            indx += 1
        self.popMenu.exec_(pos)
        self.btnSysMenu.setFocus()
    # def on_context_menu(self, point):
    #     print(point)
    #     self.popMenu.exec_(self.button.mapToGlobal(point)) 

    def btns_click(self, btnid):
        # curclassname = self.tabWidget.tabText(0)
        query = QSqlQuery(self.db)
        # cur = conn.cursor()
        today = datetime.date.today()
        self.g_curbtn = str(btnid).zfill(2)
        if self.g_curbtn not in self.dict_choices:
            self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_new)
            query.exec_("select count(*) from tmprecord where stusn='" + str(self.g_curbtn) + "'")
            query.next()            
            if query.value(0) == 0:
                query.prepare("insert into tmprecord (classname, stusn, datequestion) values (:classname, :stusn, :datequestion)")
                query.bindValue(":classname", self.g_curClassName)
                query.bindValue(":stusn", self.g_curbtn)
                query.bindValue(":datequestion", today)
                query.exec_() 
                
            self.dict_choices[self.g_curbtn] = "111"
        else:
            self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_old)
            self.btngroup.button(int(self.g_curbtn)).setIcon(QIcon())            
            query.exec_("delete from tmprecord where stusn='"+ str(self.g_curbtn) + "'")            
            self.dict_choices.pop(self.g_curbtn)

        self.btnSysMenu.setFocus()

    def exportNotice(self):
        query = QSqlQuery(self.db)
        query.exec_("select stusn, stuname, classname, rightquestions, wrongquestions from student" ) 
        lstInfo = [["学号","姓名", "班级", "回答正确次数", "回答错误次数"]]
        while(query.next()):
            lstInfo.append([query.value(0),query.value(1),query.value(2),query.value(3),query.value(4)])

        from xlwt import Workbook,easyxf
        book = Workbook(encoding='ascii')
            # 'pattern: pattern solid,  fore_colour white;'
        style = easyxf(
            'font: height 280, name 黑体;'
            'align: vertical center, horizontal center;'
            )
        style2 = easyxf('font: height 260, name 仿宋_GB2312, bold True; align: vertical center, horizontal left;')
        style3 = easyxf('font: height 260, name 仿宋_GB2312, bold True; align: vertical center, horizontal left, wrap True;')

        sheet1 = book.add_sheet('学生提问情况汇总',cell_overwrite_ok=True)
        # sheet1.write(0,7,flagtxt, easyxf('font: height 200, name 黑体;align: vertical center, horizontal right;'))
        sheet1.write_merge(0,0,0,4, '学生提问情况汇总表',style)
        sheet1.row(0).height_mismatch = 1
        sheet1.row(0).height = 5*256

        sheet1.col(0).width = 10*256
        sheet1.col(1).width = 25*256
        sheet1.col(2).width = 25*256
        sheet1.col(3).width = 20*256
        sheet1.col(4).width = 20*256
        
        tmprows = 1
        for item in lstInfo:
            stusn               = item[0]
            stuname             = item[1]
            classname           = item[2]
            rightquestions      = item[3]
            wrongquestions      = item[4]

            sheet1.write(tmprows,0,stusn, style2)
            sheet1.write(tmprows,1,stuname, style2)
            sheet1.write(tmprows,2,classname, style2)
            sheet1.write(tmprows,3,rightquestions, style2)
            sheet1.write(tmprows,4,wrongquestions, style2)
            tmprows += 1
        # print(tmprows)
        sheet1.header_str = "".encode()
        sheet1.footer_str = "".encode()

        # book.save('d:/simple.xls')
        # print(QDir.home().dirName() , QDir.homePath ())
        filename = QDir.homePath () + "\学生提问情况汇总表.xls" 
        try:
            book.save(filename)
        except  Exception as e:
            QMessageBox.warning(self, "写入错误", "错误号:"+str(e.errno)+"\n错误描述:"+e.strerror+"\n请关闭已经打开的%s文档!" % filename)
        QMessageBox.about (self, "导出成功", "请查看文档:%s" % filename)

    def aboutMe(self):
        strinfo = """本软件采用python3.4编写,界面采用qt4.8的python绑定。
                    \n版本所有:汕头市大华路第一小学赵小娜老师。
                    \n有任何问题请反馈至[email protected]。
                    """
        QMessageBox.information(None, "关于", strinfo)
        
    def initStudent(self):
        query = QSqlQuery(self.db)
        ret = query.exec_("update student set wrongquestions=0") 
        ret = query.exec_("update student set rightquestions=0")  
        QMessageBox.information(None, "提示", "已清除所有学生的累计提问情况。")


    def deleteTmpdata(self):
        query = QSqlQuery(self.db)
        ret = query.exec_("delete from tmprecord where 1=1" )   
        if self.g_curClassName != "":     
            QMessageBox.information(None, "提示", "已清除本次软件启动后的所有已提问过的学生。")
  
    def changeTab(self):
        # pass
        curtab = self.tabWidget.currentIndex()
        # print(curtab, "-")
        if curtab == 1:  ## when click the second tab page ,then pass.
            return
            
        # cur = conn.cursor()
        query = QSqlQuery(self.db)

        ## if current classname is null, then set current tabpage display the first class of classtable
        if self.g_curClassName == "":
            ret = query.exec_("select classname from classtable")
            query.next()
            self.g_curClassName = query.value(0)
            
        self.tabWidget.setTabText(0, self.g_curClassName)
        # print(1)
        strwhere = " and classname like '" + self.g_curClassName + "' ORDER BY stusn"

        self.g_curbtn = ""
        self.dict_choices = {}
        self.studentSnlst = []

        ## clearn the question data of temp record .
        ret= query.exec_("delete from tmprecord where 1=1")
        ret = query.exec_("select stusn, stuname from student where 1=1 " + strwhere)

        ## now update the global data "self.btngroup"
        for indx in range(0, 56):
            self.btngroup.button(indx+1).setText("")
            self.btngroup.button(indx+1).setMyarg(None)       
            self.btngroup.button(indx+1).setStyleSheet(stylesheetstr_old)
            self.btngroup.button(indx+1).setIcon(QIcon())
            self.btngroup.button(indx+1).setEnabled(False)
            self.studentSnlst.append([indx+1,])

        inum = 0
        while (query.next()): 
            inum += 1            
            self.btngroup.button(inum).setText(query.value(1))
            self.btngroup.button(inum).setMyarg(query.value(0))       
            self.btngroup.button(inum).setStyleSheet(stylesheetstr_old)
            self.btngroup.button(inum).setIcon(QIcon())
            self.btngroup.button(inum).setEnabled(True)

        # print(inum, len(self.btngroup.buttons()))        

        self.group_animation = groupAnimation(self.studentSnlst, self.btngroup)

    def mousePressEvent(self, event):
        # print('a')
        if event.button() == Qt.RightButton:
            QDialog.mousePressEvent(self,event)
            return
        # print(event.sender(), event.button())
        self.offset = event.pos()
        # print(self.offset)

    def mouseMoveEvent(self, event):
        # print('sss')
        if hasattr(self, 'offset'):
            x=event.globalX()
            y=event.globalY()
            x_w = self.offset.x()
            y_w = self.offset.y()
            self.move(x-x_w, y-y_w)
        else:
            pass

    #######======= studentModel ============###############
    def newStudent(self):
        # Calc the missing number:
        row = self.StudentModel.rowCount()

        if row > 0:
            oldNumList = []
            for i in range(0, row):
                oldNumList.append(int(self.StudentModel.index(i,2).data()))
            
            allNumberList = list(range(1, oldNumList[-1]+1))
            for i in range(0, allNumberList[-1]):
                if oldNumList[i] != allNumberList[i]:
                    missingNum = allNumberList[i]
                    break
            if len(oldNumList) == len(allNumberList):
                missingNum = allNumberList[i] +1
        else:
            missingNum = 1

        self.StudentModel.insertRow(row)
        self.StudentView.scrollToBottom()
        self.StudentModel.setData(self.StudentModel.index(row, 1), self.g_curClassName)
        self.StudentModel.setData(self.StudentModel.index(row, 2), str(missingNum).zfill(2))
        self.StudentModel.setData(self.StudentModel.index(row, 4), 0)
        self.StudentModel.setData(self.StudentModel.index(row, 5), 0)

    def removeStudent(self):
        index = self.StudentView.currentIndex()
        row = index.row()             
        if QMessageBox.question(self, "删除确认", "是否要删除当前选中记录?", "确定", "取消") == 0:
            self.StudentModel.removeRows(row, 1)
            self.StudentModel.submitAll()
            self.StudentModel.database().commit()

    def revertStudent(self):
        self.StudentModel.revertAll()
        self.StudentModel.database().rollback()

    def saveStudent(self):
        self.StudentModel.database().transaction()
        if self.StudentModel.submitAll():
            self.StudentModel.database().commit()
            # print("save success!  ->commit")
        else:
            self.StudentModel.revertAll()
            self.StudentModel.database().rollback()

    #######======= classModel ============###############
    def newClass(self):
        row = self.ClassnameModel.rowCount()
        self.ClassnameModel.insertRow(row)

    def removeClass(self):
        index = self.ClassnameView.currentIndex()
        row = index.row()   
        curClassname =  index.sibling(index.row(),0).data()
        strwhere = "classname like '" + curClassname + "'"
        self.StudentModel.setFilter(strwhere)
        self.StudentModel.select()
        # print(self.StudentModel.rowCount(), "----", )
        if QMessageBox.question(self, "删除确认", "删除班级意味着会删除本班所有人员信息。是否要删除当前选中记录?", "确定", "取消") == 0:
            self.ClassnameModel.removeRows(row, 1)
            self.ClassnameModel.submitAll()
            self.ClassnameModel.database().commit()

            self.StudentModel.removeRows(0, self.StudentModel.rowCount())
            self.StudentModel.submitAll()
            self.StudentModel.database().commit()

    def revertClass(self):
        self.ClassnameModel.revertAll()
        self.ClassnameModel.database().rollback()

    def saveClass(self):
        query = QSqlQuery(self.db)

        # record the old class name
        lstOldClassName = {}
        lstOldClassid = []
        query.exec_("select rowid, classname from classtable" )        
        while(query.next()):
            lstOldClassName[query.value(0)] = query.value(1)
            lstOldClassid.append(query.value(0))
        # print(lstOldClassName)

        # Update the class Table
        self.ClassnameModel.database().transaction()
        if self.ClassnameModel.submitAll():
            self.ClassnameModel.database().commit()
            # print("save success!  ->commit")
        else:
            QMessageBox.warning(None, "错误",  "请检查班级中名称,不能出现同名班级!")
            self.ClassnameModel.revertAll()
            self.ClassnameModel.database().rollback()

        # print(lstOldClassid)

        lstNewClassName = {}
        query.exec_("select rowid, classname from classtable where rowid in " + str(tuple(lstOldClassid)) )        
        while(query.next()):
            lstNewClassName[query.value(0)] = query.value(1)            

        # print(lstOldClassName, '=========')
        # print(lstNewClassName, '~~~~~~~~~')

        for i in lstOldClassName:
            oldclassname = lstOldClassName[i]
            newclassname = lstNewClassName[i]
            if oldclassname != newclassname:
                # print(oldclassname, newclassname, '++++++++')
                # print("update student set classname=" + newclassname + " where classname='" + oldclassname + "'")
                query.exec_("update student set classname='" + newclassname + "' where classname='" + oldclassname + "'")
                self.StudentModel.setFilter("classname = '" + newclassname + "'")
                self.StudentModel.select()

        lstClassName = []      
        query.exec_("select classname from classtable" ) 
        while(query.next()):
            lstClassName.append(query.value(0))
        self.StudentView.setItemDelegateForColumn(1,  ComboBoxDelegate(self, lstClassName, self.db))

    def dbclick(self, indx):
        if type(indx.sibling(indx.row(),0).data()) != QPyNullVariant:
            classname = indx.sibling(indx.row(),0).data()
            
            strwhere = "classname like '" + classname + "'"
            self.StudentModel.setFilter(strwhere)
            self.StudentModel.setSort(2, Qt.AscendingOrder)
            self.StudentModel.select()
            
            self.g_curClassName = classname
            self.tabWidget.setTabText(0, self.g_curClassName)

    def dbclick2(self, indx):
        if indx.column() == 2:
            self.StudentView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        else:
            self.StudentView.setEditTriggers(QAbstractItemView.DoubleClicked)
        

    def genTwoTab(self, tabtitle=""):
        # Create the tab title sytle.
        tabtitle = QLabel()
        tabtitle.setFont(QFont('Courier New', 20))
        tabtitle.setText("班级学生信息管理")
        tabtitle.setStyleSheet("border: 1px solid blue; color:rgba(0,0,255, 220);\
            background-color:rgba(201,201,201,60);\
            border-radius: 6px; \
            padding: 1px 18px 1px 20px;\
            min-width: 8em;")
        tabtitle.setMinimumHeight(50);
        titleLayout = QHBoxLayout()
        titleLayout.addWidget(tabtitle)
        titleLayout.setAlignment(tabtitle, Qt.AlignCenter)

       
        # Create the classnameView
        self.ClassnameView = QTableView()
        self.ClassnameModel = QSqlTableModel(self.ClassnameView)
        self.ClassnameModel.setTable("classtable")
        # self.ClassnameModel.setRelation(2, QSqlRelation("mentalmodel", "id", "name"));
        self.ClassnameModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.ClassnameModel.select()

        self.ClassnameModel.setHeaderData(0, Qt.Horizontal, "班级名称")

        # for indx, iheader in enumerate(["classid", "classname"]):
        #     self.ClassnameModel.setHeaderData(indx+1, Qt.Horizontal, iheader)
    
        self.ClassnameView.setModel(self.ClassnameModel)
        # self.ClassnameView.setColumnHidden(0, True)
        # self.ClassnameView.show()
        self.ClassnameView.verticalHeader().setFixedWidth(30)
        self.ClassnameView.verticalHeader().setStyleSheet("color: red;font-size:20px; ");
        self.ClassnameView.setStyleSheet("QTableView{background-color: rgb(250, 250, 200, 0);"  
                    "alternate-background-color: rgb(141, 163, 0);}"
                    "QTableView::item:hover {background-color: rgba(100,200,220,100);} ") 
        self.ClassnameView.setStyleSheet("font-size:16px; ");
        self.ClassnameView.setSelectionMode(QAbstractItemView.SingleSelection)
        # self.ClassnameView.dataChanged.connect(self.dataChanged)

        # self.ClassnameView.setSizePolicy(QSizePolicy.Expanding,     QSizePolicy.Expanding)

        # the second list
        self.StudentView = QTableView()
        self.StudentModel = QSqlTableModel(self.StudentView)
        self.StudentModel.setTable("student")
        # self.StudentModel.setRelation(2, QSqlRelation("mentalmodel", "id", "name"));
        self.StudentModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        # self.StudentModel.select()

        query = QSqlQuery(self.db)
        strwhere = " 1=1 "
        if self.g_curClassName == "":
            ret = query.exec_("select classname from classtable")
            query.next()
            firstClassName = query.value(0)
            strwhere += " and classname like '" + firstClassName + "'"
            
        self.StudentModel.setFilter(strwhere)
        self.StudentModel.select()

        for indx, iheader in enumerate(["班级名称", "学生编号", "学生姓名", "答对次数", "答错次数"]):
            self.StudentModel.setHeaderData(indx+1, Qt.Horizontal, iheader)
    
        self.StudentView.setModel(self.StudentModel)
        self.StudentView.setColumnHidden(0, True)

        # query = QSqlQuery(self.db)  
        lstClassName = []      
        query.exec_("select classname from classtable" ) 
        while(query.next()):
            lstClassName.append(query.value(0))

        self.StudentView.setItemDelegateForColumn(1,  ComboBoxDelegate(self, lstClassName, self.db))
        # self.StudentView.show()
        self.StudentView.verticalHeader().setFixedWidth(30)
        self.StudentView.verticalHeader().setStyleSheet("color: red;font-size:20px; background-color: rgb(250, 250, 200, 100)");
        self.StudentView.setStyleSheet("QTableView{background-color: rgb(250, 250, 200, 0);"  
                    "alternate-background-color: rgb(141, 163, 250);}"
                    "QTableView::item:hover {background-color: rgba(10,200,100,200);} "
                    ) 
        self.StudentView.setStyleSheet("font-size:16px;")
        self.StudentView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.StudentView.doubleClicked.connect(self.dbclick2)

        btn_lst1_layout = QGridLayout()
        newusrbtn       = QPushButton("新增")
        savebtn         = QPushButton("保存")
        revertbtn       = QPushButton("撤销")
        removebtn       = QPushButton("删除")
        btn_lst1_layout.addWidget(newusrbtn, 0, 0)
        btn_lst1_layout.addWidget(savebtn, 0, 1)
        btn_lst1_layout.addWidget(revertbtn, 1, 0)
        btn_lst1_layout.addWidget(removebtn, 1, 1)

        newusrbtn.clicked.connect(self.newClass)
        savebtn.clicked.connect(self.saveClass)
        revertbtn.clicked.connect(self.revertClass)
        removebtn.clicked.connect(self.removeClass)

        self.ClassnameView.doubleClicked.connect(self.dbclick)
        

        btnbox2 = QDialogButtonBox(Qt.Horizontal)
        newusrbtn2       = QPushButton("新增")
        savebtn2         = QPushButton("保存")
        revertbtn2       = QPushButton("撤销")
        removebtn2       = QPushButton("删除")
        btnbox2.addButton(newusrbtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(savebtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(revertbtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(removebtn2, QDialogButtonBox.ActionRole);

        newusrbtn2.clicked.connect(self.newStudent)
        savebtn2.clicked.connect(self.saveStudent)
        revertbtn2.clicked.connect(self.revertStudent)
        removebtn2.clicked.connect(self.removeStudent)

        # left list layout
        lst_layout_1 = QVBoxLayout()
        lst_layout_1.addWidget(self.ClassnameView)
        lst_layout_1.addLayout(btn_lst1_layout)

        lst_layout_2 = QVBoxLayout()
        lst_layout_2.addWidget(self.StudentView)
        lst_layout_2.addWidget(btnbox2)
        
        lstlayout = QHBoxLayout()
        lstlayout.setMargin(5)
        # lstlayout.addLayout(findbox)
        lstlayout.addLayout(lst_layout_1, 2)
        lstlayout.setMargin(5)
        lstlayout.addLayout(lst_layout_2, 5)
            
        labelClass = QLabel("")
        labelClass.setStyleSheet("background-color:rgba(255, 255, 255,0); color:rgba(0,0,0,0);")
        labelClass.setFixedHeight(40)
        # labelClass.setFixedWidth(100)
        # labelClass.setFont(QFont('宋体', 10))

        bottomlayout = QHBoxLayout()        
        bottomlayout.addWidget(labelClass)        

        tab2layout = QVBoxLayout()
        tab2layout.addLayout(titleLayout)       
        tab2layout.addLayout(lstlayout)
        tab2layout.addLayout(bottomlayout)
        self.w2.setLayout(tab2layout)
        self.w2.setStyleSheet("background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff, stop: 1 #228888);")
      
    def genOneTab(self):

        tabtitle = QLabel()
        # tabtitle.setFixedHeight(40)
        # tabtitle.setFixedWidth(160)        
        self.btn_start = MyButton("开始")
        self.choicenum_text = QComboBox()
        self.choicenum_text.setObjectName('w1combonums')
        # self.w1title.setStyleSheet("background-image:url('image/panelbg.jpg');")
        
        # Set the title style                
        tabtitle.setFont(QFont('Courier New', 20))
        tabtitle.setText("随堂提问演板")
        tabtitle.setStyleSheet("border: 1px solid blue; color:rgba(0,0,255, 220);\
            background-color:rgba(201,201,201,60);\
            border-radius: 6px; \
            padding: 1px 18px 1px 20px;\
            min-width: 8em;")
        tabtitle.setMinimumHeight(50);
        titleLayout = QHBoxLayout()
        titleLayout.addWidget(tabtitle)
        titleLayout.setAlignment(tabtitle, Qt.AlignCenter)
       
        btnlayout = QGridLayout()
        tmpnum = 0
        for inum in range(0,56):
            irow = tmpnum // g_cols
            icol = tmpnum % g_cols
            tmpnum += 1
            btnlayout.setRowMinimumHeight(irow, 80)
            tmpbtn = MyButton("")
            tmpbtn.setMyarg(None)
            # tmpbtn.setFixedHeight(20)
            tmpbtn.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding))
            tmpbtn.setStyleSheet("border: 1px solid rgb(55,55,255,100);background-color: rgba(255,255,255,20);font-size:16px;")
            self.connect(tmpbtn,  SIGNAL("myslot(PyQt_PyObject)"), self.myslot)
            tmpbtn.setAutoDefault(False)
            self.btngroup.addButton(tmpbtn, inum+1) # stusn is from 1 start

            btnlayout.addWidget(tmpbtn, irow, icol)


        self.btn_start.setIcon(QIcon("image/start.png"))
        self.btn_start.setStyleSheet("border: 1px solid yellow;")
        self.btn_start.setFixedHeight(40)
        self.btn_start.setFixedWidth(100)
        self.btn_start.setFont(QFont('宋体', 18))
        # self.choicenum_text.setFixedHeight(45)
        # self.choicenum_text.setFixedWidth(60)

        ## Set the combox number style
        self.choicenum_text.setFont(QFont('Courier New', 20))
        self.choicenum_text.setFixedHeight(45)
        self.choicenum_text.setStyleSheet("border: 2px solid blue; color:red;font-weight:light;font-size:26px;\
            border-radius: 6px; \
            min-width: 2em; ")
        self.choicenum_text.setEditable(True)
        self.choicenum_text.lineEdit().setReadOnly(True);
        self.choicenum_text.lineEdit().setAlignment(Qt.AlignCenter);

        model = self.choicenum_text.model()
        for row in list(range(1, 7)):
            item = QStandardItem(str(row))
            item.setTextAlignment(Qt.AlignCenter)
            item.setForeground(QColor('red'))
            item.setBackground(QColor(0,200,50, 130))
            model.appendRow(item)
        self.choicenum_text.setCurrentIndex(2)
        # self.choicenum_text.setStyleSheet ("QComboBox::drop-down {border-width: 100px;}")
        # self.choicenum_text.setStyleSheet ("QComboBox::down-arrow {image: url(image/downarrow.png);top: 10px;left: 1px;}")

        bottomlayout = QHBoxLayout()
        bottomlayout.setSizeConstraint(QLayout.SetFixedSize)
        bottomlayout.addStretch(10)
        bottomlayout.addWidget(self.btn_start)
        bottomlayout.setSpacing(5)
        bottomlayout.addWidget(self.choicenum_text)

        tab1layout = QVBoxLayout()
        tab1layout.addLayout(titleLayout)       
        tab1layout.addLayout(btnlayout)
        tab1layout.addLayout(bottomlayout)
                
        self.w1.setLayout(tab1layout)
        self.w1.setStyleSheet("background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff, stop: 1 #228888);")
         
    def startChoice(self, usernum="", oldbtn=""): 
        # print(oldbtn, 1)

        if oldbtn == "":
            self.dict_choices = {}

        strwhere = " and classname like '" + self.g_curClassName + "'"

        allstudent = []
        lstrecord = []
        query = QSqlQuery(self.db)        
        query.exec_("select stusn from tmprecord where 1=1 " + strwhere) 
        while(query.next()):
            lstrecord.append(query.value(0))
        # print(lstrecord, 'record', "select stusn from student where stusn not in " + str(tuple(lstrecord)))

        query.exec_("select stusn from student where stusn not in " + str(tuple(lstrecord)) + strwhere)
        while(query.next()):
            allstudent.append(query.value(0))

        if usernum == "":
            nums = int(self.choicenum_text.currentText())
        else:
            nums = usernum
        if nums >= len(allstudent):
            query.exec_("delete from tmprecord where 1=1 " + strwhere) #delete tmp date no today            
            allstudent = []
            query.exec_("select stusn from student where 1=1 " + strwhere)
            while(query.next()):
                allstudent.append(query.value(0))
        
        if oldbtn == "":
            random.seed()
            lstchoices = random.sample(allstudent, nums)
            for ibtn in lstchoices:
                self.dict_choices[ibtn] = "111"

            self.group_animation.start()
            QTimer.singleShot(1200, self.stopmovie)
        else:
            random.seed()
            otherbtn = random.sample(allstudent, 1)[0]
            # self.btngroup.button(int(otherbtn)).setFocus()
            self.dict_choices.pop(oldbtn)
            self.dict_choices[otherbtn] = '111'
            self.stopmovie()
        self.btnSysMenu.setFocus()

    def stopmovie(self):
        self.group_animation.stop()
        for isn in self.studentSnlst:
            # print(isn)
            self.btngroup.button(int(isn[0])).setStyleSheet(stylesheetstr_old)
            self.btngroup.button(int(isn[0])).setIcon(QIcon())
        
        classname = self.tabWidget.tabText(0)
        query = QSqlQuery(self.db)        
        today = datetime.date.today()
        for ibtn in self.dict_choices:
            self.btngroup.button(int(ibtn)).setStyleSheet(stylesheetstr_new)
            query.exec_("select count(*) from tmprecord where stusn='" + str(ibtn) + "'")
            query.next()
            if query.value(0) == 0:               
                query.prepare("insert into tmprecord (classname, stusn, datequestion) values (:classname, :stusn, :datequestion)")
                query.bindValue(":classname", classname)
                query.bindValue(":stusn", ibtn)
                query.bindValue(":datequestion", today)
                query.exec_()
    
    def answerRight(self):
        # print(self.g_curbtn)
        value = self.g_curbtn
        if value not in self.dict_choices:
            return

        self.btngroup.button(int(value)).setIcon(QIcon("image/smile.png"))
        self.btngroup.button(int(value)).setIconSize(QSize(20,20))
        
        query = QSqlQuery(self.db)
        query.exec_("select rightquestions from student where stusn='" + value + "'")
        query.next()
        studentRightQuestions = query.value(0) + 1
        query.exec_("update student set rightquestions=" + str(studentRightQuestions) + " where stusn='" + value + "'")
                
        ###########
        if self.dict_choices[value] == "101":
            query.exec_("select wrongquestions from student where stusn='" + value + "'")
            query.next()
            studentWrongQuestions = query.value(0) - 1
            query.exec_("update student set wrongquestions=" + str(studentWrongQuestions) + " where stusn='" + value + "'")
            
        self.dict_choices[value] = "011"

    def answerWrong(self):
        value = self.g_curbtn
        if value not in self.dict_choices:
            return

        self.btngroup.button(int(value)).setIcon(QIcon("image/cry.png"))
        self.btngroup.button(int(value)).setIconSize(QSize(20,20))
        # self.btngroup.button(int(value)).setStyleSheet("border-image: url(image/ex_stu.png);")
        
        query = QSqlQuery(self.db)
        query.exec_("select wrongquestions from student where stusn='" + value + "'")
        query.next()
        studentWrongQuestions = query.value(0) + 1
        query.exec_("update student set wrongquestions=" + str(studentWrongQuestions) + " where stusn='" + value + "'")
        
        if self.dict_choices[value] == "011":
            query.exec_("select rightquestions from student where stusn='" + value + "'")
            query.next()
            studentRightQuestions = query.value(0) - 1
            query.exec_("update student set rightquestions=" + str(studentRightQuestions) + " where stusn='" + value + "'")
            
        self.dict_choices[value] = "101"

    def resetStudent(self):
        value = self.g_curbtn
        if value not in self.dict_choices:
            return

        query = QSqlQuery(self.db)

        if self.dict_choices[value] == "011":        
            query.exec_("select rightquestions from student where stusn='" + value + "'")
            query.next()
            studentRightQuestions = query.value(0) - 1
            query.exec_("update student set rightquestions=" + str(studentRightQuestions) + " where stusn='" + value + "'")

        if self.dict_choices[value] == "101":
            query.exec_("select wrongquestions from student where stusn='" + value + "'")
            query.next()
            studentWrongQuestions = query.value(0) - 1
            query.exec_("update student set wrongquestions=" + str(studentWrongQuestions) + " where stusn='" + value + "'")
            
        self.startChoice(usernum=1, oldbtn=value)
        # print("---reset___")

        # curmenu.actions()[0].setEnabled(True)
        # curmenu.actions()[1].setEnabled(True)
        # self.choiceOneStudent(value)

    def createDb(self):
        conn = sqlite3.connect("studentNew.db") 
        cur = conn.cursor()
        sqlstr = 'create table student (id integer primary key, \
            classname varchar(20), \
            stusn varchar(20), \
            stuname varchar(20), \
            rightquestions integer, \
            wrongquestions integer, \
            FOREIGN KEY(classname) REFERENCES classtable(classname))'
        # print(sqlstr)

        sqlstr2 = 'create table tmprecord (id integer primary key, \
            classname varchar(20), \
            stusn varchar(20), \
            datequestion date)'

        sqlstr3 = 'create table classtable (classname varchar(20) PRIMARY KEY)'
        
        cur.execute(sqlstr3)
        conn.commit()
        cur.execute(sqlstr2)
        conn.commit()
        cur.execute(sqlstr)
        conn.commit()

        strdelete = "delete from student where 1=1"
        cur.execute(strdelete)
        conn.commit()
        strdelete = "delete from tmprecord where 1=1"
        cur.execute(strdelete)
        conn.commit()
        # print(sqlstr2)

        # cur.execute(sqlstr) 
        # conn.commit()
        # cur.execute(sqlstr2) 
        # conn.commit()

        # insert example data
        strsql = "insert into classtable values (?)"
        cur.execute(strsql, ("三(3)班",))
        conn.commit()
        cur.execute(strsql, ("三(4)班",))
        conn.commit()


        a03lst = ["曾忆谊","赵佳泉","翁文秀","林珑","郑铭洁","林泽思","吴崇霖","陈思嘉","欧阳月孜","郭展羽","詹伟哲","黄佳仪","杨秋霞","周奕子","林楚杰","欧伊涵","许腾誉","陈唯凯","陈树凯","林彦君","张钰佳","高锴","杨博凯","林妙菲","林楚鸿","陈展烯","姚静茵","吴欣桐","范思杰","肖佳","马思广","许一帆","姚奕帆","陈海珣","吴黛莹","吴育桐","肖凯帆","林欣阳","叶茂霖","姚楷臻","陈嘉豪","陈琦","杨子楷","陈炎宏","陈幸仪","杨景畅","罗暖婷","郑馨"]
        a04lst = ["罗恩琪","王可","曾祥威","谢濡婷","温嘉凯","许洁仪","肖欣淇","陈凯佳","林天倩","李乐海","吴文慧","黄文婷","万誉","陈进盛","张裕涵","陈振嘉","王巧玲","林珮琪","陈炜楷","杨健","赵泽锴","张凤临","蔡子丹","陈烨杰","廖妍希","林树超","夏培轩","陈锦森","李星","蔡依婷","姚容创","姚凯扬","沈嘉克","周凡","张玉川","邱金迅","陈菲敏","陈星翰","朱煜楷","郑泽洪","钱剑非","罗奕丰","陈杜炜","林知钦"]
        strsql = "insert into student values (?, ?, ?, ?,?,?)" 
        for i in list(range(0,len(a03lst))):
            cur.execute(strsql, (None, "三(3)班", str(i+1).zfill(2), a03lst[i], 0, 0))
            conn.commit()
        strsql = "insert into student values (?, ?, ?, ?,?,?)" 
        for i in list(range(0,len(a04lst))):
            cur.execute(strsql, (None, "三(4)班", str(i+1).zfill(2), a04lst[i], 0, 0))
            conn.commit()
        cur.close()
Ejemplo n.º 48
0
class ParentAction(object):
    def __init__(self, iface, settings, controller, plugin_dir):
        ''' Class constructor '''

        # Initialize instance attributes
        self.giswater_version = "3.0"
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.settings = settings
        self.controller = controller
        self.plugin_dir = plugin_dir
        self.dao = self.controller.dao
        self.schema_name = self.controller.schema_name
        self.project_type = None
        self.file_gsw = None
        self.gsw_settings = None

        # Get files to execute giswater jar (only in Windows)
        if 'nt' in sys.builtin_module_names:
            self.plugin_version = self.get_plugin_version()
            self.java_exe = self.get_java_exe()
            (self.giswater_file_path,
             self.giswater_build_version) = self.get_giswater_jar()

    def set_controller(self, controller):
        """ Set controller class """

        self.controller = controller
        self.schema_name = self.controller.schema_name

    def get_plugin_version(self):
        ''' Get plugin version from metadata.txt file '''

        # Check if metadata file exists
        metadata_file = os.path.join(self.plugin_dir, 'metadata.txt')
        if not os.path.exists(metadata_file):
            message = "Metadata file not found" + metadata_file
            self.controller.show_warning(message, parameter=metadata_file)
            return None

        metadata = ConfigParser.ConfigParser()
        metadata.read(metadata_file)
        plugin_version = metadata.get('general', 'version')
        if plugin_version is None:
            message = "Plugin version not found"
            self.controller.show_warning(message)

        return plugin_version

    def get_giswater_jar(self):
        ''' Get executable Giswater file and build version from windows registry '''

        reg_hkey = "HKEY_LOCAL_MACHINE"
        reg_path = "SOFTWARE\\Giswater\\" + self.giswater_version
        reg_name = "InstallFolder"
        giswater_folder = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
        if giswater_folder is None:
            message = "Cannot get giswater folder from windows registry"
            self.controller.log_info(message, parameter=reg_path)
            return (None, None)

        # Check if giswater folder exists
        if not os.path.exists(giswater_folder):
            message = "Giswater folder not found"
            self.controller.log_info(message, parameter=giswater_folder)
            return (None, None)

        # Check if giswater executable file file exists
        giswater_file_path = giswater_folder + "\giswater.jar"
        if not os.path.exists(giswater_file_path):
            message = "Giswater executable file not found"
            self.controller.log_info(message, parameter=giswater_file_path)
            return (None, None)

        # Get giswater major version
        reg_name = "MajorVersion"
        major_version = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
        if major_version is None:
            message = "Cannot get giswater major version from windows registry"
            self.controller.log_info(message, parameter=reg_path)
            return (giswater_file_path, None)

        # Get giswater minor version
        reg_name = "MinorVersion"
        minor_version = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
        if minor_version is None:
            message = "Cannot get giswater minor version from windows registry" + reg_path
            self.controller.log_info(message, parameter=reg_path)
            return (giswater_file_path, None)

        # Get giswater build version
        reg_name = "BuildVersion"
        build_version = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
        if build_version is None:
            message = "Cannot get giswater build version from windows registry"
            self.controller.log_info(message, parameter=reg_path)
            return (giswater_file_path, None)

        giswater_build_version = major_version + '.' + minor_version + '.' + build_version

        return (giswater_file_path, giswater_build_version)

    def get_java_exe(self):
        ''' Get executable Java file from windows registry '''

        reg_hkey = "HKEY_LOCAL_MACHINE"
        reg_path = "SOFTWARE\\JavaSoft\\Java Runtime Environment"
        reg_name = "CurrentVersion"
        java_version = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)

        # Check if java version exists (64 bits)
        if java_version is None:
            reg_path = "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment"
            java_version = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
            # Check if java version exists (32 bits)
            if java_version is None:
                message = "Cannot get current Java version from windows registry"
                self.controller.log_info(message, parameter=reg_path)
                return None

        # Get java folder
        reg_path += "\\" + java_version
        reg_name = "JavaHome"
        java_folder = utils_giswater.get_reg(reg_hkey, reg_path, reg_name)
        if java_folder is None:
            message = "Cannot get Java folder from windows registry"
            self.controller.log_info(message, parameter=reg_path)
            return None

        # Check if java folder exists
        if not os.path.exists(java_folder):
            message = "Java folder not found"
            self.controller.log_info(message, parameter=java_folder)
            return None

        # Check if java executable file exists
        java_exe = java_folder + "/bin/java.exe"
        if not os.path.exists(java_exe):
            message = "Java executable file not found"
            self.controller.log_info(message, parameter=java_exe)
            return None

        return java_exe

    def execute_giswater(self, parameter):
        ''' Executes giswater with selected parameter '''

        if self.giswater_file_path is None or self.java_exe is None:
            return

        # Save database connection parameters into GSW file
        self.save_database_parameters()

        # Check if gsw file exists. If not giswater will open with the last .gsw file
        if self.file_gsw is None:
            self.file_gsw = ""
        if self.file_gsw:
            if self.file_gsw != "" and not os.path.exists(self.file_gsw):
                message = "GSW file not found"
                self.controller.show_info(message, parameter=self.file_gsw)
                self.file_gsw = ""

        # Start program
        aux = '"' + self.giswater_file_path + '"'
        if self.file_gsw != "":
            aux += ' "' + self.file_gsw + '"'
            program = [
                self.java_exe, "-jar", self.giswater_file_path, self.file_gsw,
                parameter
            ]
        else:
            program = [
                self.java_exe, "-jar", self.giswater_file_path, "", parameter
            ]

        self.controller.log_info(str(program))
        self.controller.start_program(program)

        # Compare Java and Plugin versions
        if self.plugin_version <> self.giswater_build_version:
            msg = ("Giswater and plugin versions are different. "
                   "Giswater version: " + self.giswater_build_version + ""
                   " - Plugin version: " + self.plugin_version)
            self.controller.show_info(msg, 10)
        # Show information message
        else:
            message = "Executing..."
            self.controller.show_info(message, parameter=aux)

    def set_java_settings(self, show_warning=True):

        # Get giswater properties file
        users_home = os.path.expanduser("~")
        filename = "giswater_" + self.giswater_version + ".properties"
        java_properties_path = users_home + os.sep + "giswater" + os.sep + "config" + os.sep + filename
        if not os.path.exists(java_properties_path):
            message = "Giswater properties file not found"
            if show_warning:
                self.controller.show_warning(
                    message, parameter=str(java_properties_path))
            return False

        self.java_settings = QSettings(java_properties_path,
                                       QSettings.IniFormat)
        self.java_settings.setIniCodec(sys.getfilesystemencoding())
        self.file_gsw = utils_giswater.get_settings_value(
            self.java_settings, 'FILE_GSW')

    def set_gsw_settings(self):

        if not self.file_gsw:
            self.set_java_settings(False)

        self.gsw_settings = QSettings(self.file_gsw, QSettings.IniFormat)

    def save_database_parameters(self):
        """ Save database connection parameters into GSW file """

        if self.gsw_settings is None:
            self.set_gsw_settings()

        # Get layer version
        layer = self.controller.get_layer_by_tablename('version')
        if not layer:
            return

        # Get database connection paramaters and save them into GSW file
        layer_source = self.controller.get_layer_source_from_credentials()
        if layer_source is None:
            return

        self.gsw_settings.setValue('POSTGIS_DATABASE', layer_source['db'])
        self.gsw_settings.setValue('POSTGIS_HOST', layer_source['host'])
        self.gsw_settings.setValue('POSTGIS_PORT', layer_source['port'])
        self.gsw_settings.setValue('POSTGIS_USER', layer_source['user'])
        self.gsw_settings.setValue('POSTGIS_USESSL', 'false')

    def open_web_browser(self, widget=None):
        """ Display url using the default browser """

        if widget is not None:
            url = utils_giswater.getWidgetText(widget)
            if url == 'null':
                url = 'www.giswater.org'
        else:
            url = 'www.giswater.org'

        webbrowser.open(url)

    def get_file_dialog(self, widget):
        """ Get file dialog """

        # Check if selected file exists. Set default value if necessary
        file_path = utils_giswater.getWidgetText(widget)
        if file_path is None or file_path == 'null' or not os.path.exists(
                str(file_path)):
            folder_path = self.plugin_dir
        else:
            folder_path = os.path.dirname(file_path)

        # Open dialog to select file
        os.chdir(folder_path)
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.AnyFile)
        message = "Select file"
        folder_path = file_dialog.getOpenFileName(
            parent=None, caption=self.controller.tr(message))
        if folder_path:
            utils_giswater.setWidgetText(widget, str(folder_path))

    def get_folder_dialog(self, widget):
        """ Get folder dialog """

        # Check if selected folder exists. Set default value if necessary
        folder_path = utils_giswater.getWidgetText(widget)
        if folder_path is None or folder_path == 'null' or not os.path.exists(
                folder_path):
            folder_path = os.path.expanduser("~")

        # Open dialog to select folder
        os.chdir(folder_path)
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.Directory)
        message = "Select folder"
        folder_path = file_dialog.getExistingDirectory(
            parent=None,
            caption=self.controller.tr(message),
            directory=folder_path)
        if folder_path:
            utils_giswater.setWidgetText(widget, str(folder_path))

    def load_settings(self, dialog=None):
        """ Load QGIS settings related with dialog position and size """

        if dialog is None:
            dialog = self.dlg

        try:
            width = self.controller.plugin_settings_value(
                dialog.objectName() + "_width", dialog.width())
            height = self.controller.plugin_settings_value(
                dialog.objectName() + "_height", dialog.height())
            x = self.controller.plugin_settings_value(dialog.objectName() +
                                                      "_x")
            y = self.controller.plugin_settings_value(dialog.objectName() +
                                                      "_y")
            if int(x) < 0 or int(y) < 0:
                dialog.resize(int(width), int(height))
            else:
                dialog.setGeometry(int(x), int(y), int(width), int(height))
        except:
            pass

    def save_settings(self, dialog=None):
        """ Save QGIS settings related with dialog position and size """

        if dialog is None:
            dialog = self.dlg

        self.controller.plugin_settings_set_value(
            dialog.objectName() + "_width", dialog.width())
        self.controller.plugin_settings_set_value(
            dialog.objectName() + "_height", dialog.height())
        self.controller.plugin_settings_set_value(dialog.objectName() + "_x",
                                                  dialog.pos().x() + 8)
        self.controller.plugin_settings_set_value(dialog.objectName() + "_y",
                                                  dialog.pos().y() + 31)

    def open_dialog(self,
                    dlg=None,
                    dlg_name=None,
                    maximize_button=True,
                    stay_on_top=True):
        """ Open dialog """

        if dlg is None or type(dlg) is bool:
            dlg = self.dlg

        # Manage i18n of the dialog
        if dlg_name:
            self.controller.manage_translation(dlg_name, dlg)

        # Manage stay on top and maximize button
        if maximize_button and stay_on_top:
            dlg.setWindowFlags(Qt.WindowMinimizeButtonHint
                               | Qt.WindowMaximizeButtonHint
                               | Qt.WindowStaysOnTopHint)
        elif not maximize_button and stay_on_top:
            dlg.setWindowFlags(Qt.WindowMinimizeButtonHint
                               | Qt.WindowStaysOnTopHint)
        elif maximize_button and not stay_on_top:
            dlg.setWindowFlags(Qt.WindowMaximizeButtonHint)

        # Open dialog
        dlg.open()

    def close_dialog(self, dlg=None):
        """ Close dialog """

        if dlg is None or type(dlg) is bool:
            dlg = self.dlg
        try:
            self.save_settings(dlg)
            dlg.close()
            map_tool = self.canvas.mapTool()
            # If selected map tool is from the plugin, set 'Pan' as current one
            if map_tool.toolName() == '':
                self.iface.actionPan().trigger()
        except AttributeError:
            pass

    def multi_row_selector(self, dialog, tableleft, tableright, field_id_left,
                           field_id_right):

        # fill QTableView all_rows
        tbl_all_rows = dialog.findChild(QTableView, "all_rows")
        tbl_all_rows.setSelectionBehavior(QAbstractItemView.SelectRows)

        query_left = "SELECT * FROM " + self.schema_name + "." + tableleft + " WHERE name NOT IN "
        query_left += "(SELECT name FROM " + self.schema_name + "." + tableleft
        query_left += " RIGHT JOIN " + self.schema_name + "." + tableright + " ON " + tableleft + "." + field_id_left + " = " + tableright + "." + field_id_right
        query_left += " WHERE cur_user = current_user)"
        self.fill_table_by_query(tbl_all_rows, query_left)
        self.hide_colums(tbl_all_rows,
                         [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
        tbl_all_rows.setColumnWidth(1, 200)

        # fill QTableView selected_rows
        tbl_selected_rows = dialog.findChild(QTableView, "selected_rows")
        tbl_selected_rows.setSelectionBehavior(QAbstractItemView.SelectRows)
        query_right = "SELECT name, cur_user, " + tableleft + "." + field_id_left + ", " + tableright + "." + field_id_right + " FROM " + self.schema_name + "." + tableleft
        query_right += " JOIN " + self.schema_name + "." + tableright + " ON " + tableleft + "." + field_id_left + " = " + tableright + "." + field_id_right
        query_right += " WHERE cur_user = current_user"
        self.fill_table_by_query(tbl_selected_rows, query_right)
        self.hide_colums(tbl_selected_rows, [1, 2, 3])
        tbl_selected_rows.setColumnWidth(0, 200)
        # Button select
        dialog.btn_select.pressed.connect(
            partial(self.multi_rows_selector, tbl_all_rows, tbl_selected_rows,
                    field_id_left, tableright, "id", query_left, query_right,
                    field_id_right))

        # Button unselect
        query_delete = "DELETE FROM " + self.schema_name + "." + tableright
        query_delete += " WHERE current_user = cur_user AND " + tableright + "." + field_id_right + "="
        dialog.btn_unselect.pressed.connect(
            partial(self.unselector, tbl_all_rows, tbl_selected_rows,
                    query_delete, query_left, query_right, field_id_right))
        # QLineEdit
        dialog.txt_name.textChanged.connect(
            partial(self.query_like_widget_text, dialog.txt_name, tbl_all_rows,
                    tableleft, tableright, field_id_right))

    def hide_colums(self, widget, comuns_to_hide):
        for i in range(0, len(comuns_to_hide)):
            widget.hideColumn(comuns_to_hide[i])

    def unselector(self, qtable_left, qtable_right, query_delete, query_left,
                   query_right, field_id_right):

        selected_list = qtable_right.selectionModel().selectedRows()
        if len(selected_list) == 0:
            message = "Any record selected"
            self.controller.show_warning(message)
            return
        expl_id = []
        for i in range(0, len(selected_list)):
            row = selected_list[i].row()
            id_ = str(qtable_right.model().record(row).value(field_id_right))
            expl_id.append(id_)
        for i in range(0, len(expl_id)):
            self.controller.execute_sql(query_delete + str(expl_id[i]))

        # Refresh
        self.fill_table_by_query(qtable_left, query_left)
        self.fill_table_by_query(qtable_right, query_right)
        self.refresh_map_canvas()

    def multi_rows_selector(self, qtable_left, qtable_right, id_ori,
                            tablename_des, id_des, query_left, query_right,
                            field_id):
        """
            :param qtable_left: QTableView origin
            :param qtable_right: QTableView destini
            :param id_ori: Refers to the id of the source table
            :param tablename_des: table destini
            :param id_des: Refers to the id of the target table, on which the query will be made
            :param query_right:
            :param query_left:
            :param field_id:
        """

        selected_list = qtable_left.selectionModel().selectedRows()

        if len(selected_list) == 0:
            message = "Any record selected"
            self.controller.show_warning(message)
            return
        expl_id = []
        curuser_list = []
        for i in range(0, len(selected_list)):
            row = selected_list[i].row()
            id_ = qtable_left.model().record(row).value(id_ori)
            expl_id.append(id_)
            curuser = qtable_left.model().record(row).value("cur_user")
            curuser_list.append(curuser)
        for i in range(0, len(expl_id)):
            # Check if expl_id already exists in expl_selector
            sql = ("SELECT DISTINCT(" + id_des + ", cur_user)"
                   " FROM " + self.schema_name + "." + tablename_des + ""
                   " WHERE " + id_des + " = '" + str(expl_id[i]) +
                   "' AND cur_user = current_user")
            row = self.controller.get_row(sql)

            if row:
                # if exist - show warning
                message = "Id already selected"
                self.controller.show_info_box(message,
                                              "Info",
                                              parameter=str(expl_id[i]))
            else:
                sql = ("INSERT INTO " + self.schema_name + "." +
                       tablename_des + " (" + field_id + ", cur_user) "
                       " VALUES (" + str(expl_id[i]) + ", current_user)")
                self.controller.execute_sql(sql)

        # Refresh
        self.fill_table_by_query(qtable_right, query_right)
        self.fill_table_by_query(qtable_left, query_left)
        self.refresh_map_canvas()

    def fill_table_psector(self,
                           widget,
                           table_name,
                           set_edit_strategy=QSqlTableModel.OnManualSubmit):
        """ Set a model with selected @table_name. Attach that model to selected table """

        # Set model
        self.model = QSqlTableModel()
        self.model.setTable(self.schema_name + "." + table_name)
        self.model.setEditStrategy(set_edit_strategy)
        self.model.setSort(0, 0)
        self.model.select()

        # Check for errors
        if self.model.lastError().isValid():
            self.controller.show_warning(self.model.lastError().text())

        # Attach model to table view
        widget.setModel(self.model)

    def update_combobox_values(self, widget, combo, x):
        """ Insert combobox.currentText into widget (QTableView) """

        index = widget.model().index(x, 4)
        widget.model().setData(index, combo.currentText())

    def fill_table(self,
                   widget,
                   table_name,
                   set_edit_strategy=QSqlTableModel.OnManualSubmit):
        """ Set a model with selected filter.
        Attach that model to selected table """

        # Set model
        self.model = QSqlTableModel()
        self.model.setTable(self.schema_name + "." + table_name)
        self.model.setEditStrategy(set_edit_strategy)
        self.model.setSort(0, 0)
        self.model.select()

        # Check for errors
        if self.model.lastError().isValid():
            self.controller.show_warning(self.model.lastError().text())
        # Attach model to table view
        widget.setModel(self.model)

    def fill_table_by_query(self, qtable, query):
        """
        :param qtable: QTableView to show
        :param query: query to set model
        """
        model = QSqlQueryModel()
        model.setQuery(query)
        qtable.setModel(model)
        qtable.show()

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())

    def query_like_widget_text(self, text_line, qtable, tableleft, tableright,
                               field_id):
        """ Fill the QTableView by filtering through the QLineEdit"""

        query = utils_giswater.getWidgetText(text_line).lower()
        sql = ("SELECT * FROM " + self.schema_name + "." + tableleft +
               " WHERE name NOT IN "
               "(SELECT name FROM " + self.schema_name + "." + tableleft + ""
               " RIGHT JOIN " + self.schema_name + "." + tableright + ""
               " ON " + tableleft + "." + field_id + " = " + tableright + "." +
               field_id + ""
               " WHERE cur_user = current_user) AND LOWER(name) LIKE '%" +
               query + "%'")
        self.fill_table_by_query(qtable, sql)

    def set_icon(self, widget, icon):
        """ Set @icon to selected @widget """

        # Get icons folder
        icons_folder = os.path.join(self.plugin_dir, 'icons')
        icon_path = os.path.join(icons_folder, str(icon) + ".png")
        if os.path.exists(icon_path):
            widget.setIcon(QIcon(icon_path))
        else:
            self.controller.log_info("File not found", parameter=icon_path)

    def check_expression(self, expr_filter, log_info=False):
        """ Check if expression filter @expr_filter is valid """

        if log_info:
            self.controller.log_info(expr_filter)
        expr = QgsExpression(expr_filter)
        if expr.hasParserError():
            message = "Expression Error"
            self.controller.log_warning(message, parameter=expr_filter)
            return (False, expr)
        return (True, expr)

    def refresh_map_canvas(self, restore_cursor=False):
        """ Refresh all layers present in map canvas """

        self.canvas.refreshAllLayers()
        for layer_refresh in self.canvas.layers():
            layer_refresh.triggerRepaint()

        if restore_cursor:
            self.set_cursor_restore()

    def set_cursor_wait(self):
        """ Change cursor to 'WaitCursor' """
        QApplication.setOverrideCursor(Qt.WaitCursor)

    def set_cursor_arrow(self):
        """ Change cursor to 'ArrowCursor' """
        QApplication.setOverrideCursor(Qt.ArrowCursor)

    def set_cursor_restore(self):
        """ Restore to previous cursors """
        QApplication.restoreOverrideCursor()

    def get_cursor_multiple_selection(self):
        """ Set cursor for multiple selection """

        path_folder = os.path.join(os.path.dirname(__file__), os.pardir)
        path_cursor = os.path.join(path_folder, 'icons', '201.png')
        if os.path.exists(path_cursor):
            cursor = QCursor(QPixmap(path_cursor))
        else:
            cursor = QCursor(Qt.ArrowCursor)

        return cursor

    def set_table_columns(self, widget, table_name):
        """ Configuration of tables. Set visibility and width of columns """

        widget = utils_giswater.getWidget(widget)
        if not widget:
            return

        # Set width and alias of visible columns
        columns_to_delete = []
        sql = ("SELECT column_index, width, alias, status"
               " FROM " + self.schema_name + ".config_client_forms"
               " WHERE table_id = '" + table_name + "'"
               " ORDER BY column_index")
        rows = self.controller.get_rows(sql, log_info=False)
        if not rows:
            return

        for row in rows:
            if not row['status']:
                columns_to_delete.append(row['column_index'] - 1)
            else:
                width = row['width']
                if width is None:
                    width = 100
                widget.setColumnWidth(row['column_index'] - 1, width)
                widget.model().setHeaderData(row['column_index'] - 1,
                                             Qt.Horizontal, row['alias'])

        # Set order
        # widget.model().setSort(0, Qt.AscendingOrder)
        widget.model().select()

        # Delete columns
        for column in columns_to_delete:
            widget.hideColumn(column)

    def connect_signal_selection_changed(self, option):
        """ Connect signal selectionChanged """

        try:
            if option == "mincut_connec":
                self.canvas.selectionChanged.connect(
                    partial(self.snapping_selection_connec))
            elif option == "mincut_hydro":
                self.canvas.selectionChanged.connect(
                    partial(self.snapping_selection_hydro))
        except Exception:
            pass

    def disconnect_signal_selection_changed(self):
        """ Disconnect signal selectionChanged """

        try:
            self.canvas.selectionChanged.disconnect()
        except Exception:
            pass

    def set_label_current_psector(self):
        sql = (
            "SELECT t1.name FROM " + self.schema_name + ".plan_psector AS t1 "
            " INNER JOIN " + self.schema_name +
            ".config_param_user AS t2 ON t1.psector_id::text = t2.value "
            " WHERE t2.parameter='psector_vdefault' AND cur_user = current_user"
        )
        row = self.controller.get_row(sql)
        if not row:
            return
        utils_giswater.setWidgetText('lbl_vdefault_psector', row[0])
Ejemplo n.º 49
0
    def reload_table_visit(self):
        feature_type = utils_giswater.get_item_data(
            self.dlg_lot, self.dlg_lot.cmb_visit_class, 2)
        object_id = utils_giswater.getWidgetText(self.dlg_lot,
                                                 self.dlg_lot.txt_filter)
        visit_start = self.dlg_lot.date_event_from.date()
        visit_end = self.dlg_lot.date_event_to.date()
        # Get selected dates
        date_from = visit_start.toString('yyyyMMdd 00:00:00')
        date_to = visit_end.toString('yyyyMMdd 23:59:59')
        if date_from > date_to:
            message = "Selected date interval is not valid"
            self.controller.show_warning(message)
            return
        visit_class_id = utils_giswater.get_item_data(
            self.dlg_lot, self.dlg_lot.cmb_visit_class, 0)
        sql = ("SELECT visitclass_id, formname, tablename FROM " +
               self.schema_name + ".config_api_visit "
               " WHERE visitclass_id ='" + str(visit_class_id) + "'")
        row = self.controller.get_row(sql, log_sql=False)

        table_name = row['tablename']
        if self.schema_name not in table_name:
            table_name = self.schema_name + "." + table_name

        # Create interval dates
        format_low = 'yyyy-MM-dd 00:00:00.000'
        format_high = 'yyyy-MM-dd 23:59:59.999'
        interval = "'{}'::timestamp AND '{}'::timestamp".format(
            visit_start.toString(format_low), visit_end.toString(format_high))

        expr_filter = ("(startdate BETWEEN {0}) AND (enddate BETWEEN {0})".
                       format(interval))
        if object_id != 'null':
            expr_filter += " AND " + str(
                feature_type) + "_id::TEXT ILIKE '%" + str(object_id) + "%'"

        expr_filter += " AND " + str(feature_type) + "_id IN ('0', "
        for i in range(len(self.ids)):
            expr_filter += "'" + str(self.ids[i]) + "', "
        expr_filter = expr_filter[:-2] + ")"

        model = QSqlTableModel()
        model.setTable(table_name)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        model.setFilter(expr_filter)
        model.sort(0, 1)
        model.select()

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())

        # Attach model to table view
        self.dlg_lot.tbl_visit.setModel(model)
Ejemplo n.º 50
0
    def populate_visits(self, widget, table_name, expr_filter=None):
        """ Set a model with selected filter. Attach that model to selected table """
        if self.schema_name not in table_name:
            table_name = self.schema_name + "." + table_name
        # Set model

        #model = CustomSqlModel()
        model = QSqlTableModel()
        model.setTable(table_name)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        model.sort(0, 1)
        if expr_filter:
            model.setFilter(expr_filter)
        model.select()

        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())

        # Attach model to table view
        widget.setModel(model)
Ejemplo n.º 51
0
class PlayerList(QDialog):
    """QtSQL Model view of the players"""
    def __init__(self, parent):
        QDialog.__init__(self)
        self.parent = parent
        self.model = QSqlTableModel(self, DBHandle.default)
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.model.setTable("player")
        self.model.setSort(1, 0)
        self.model.setHeaderData(1, Qt.Horizontal, QVariant(m18nc("Player", "Name")))
        self.model.setFilter('name not like "ROBOT %" and name not like "Robot %"')
        self.view = MJTableView(self)
        self.view.verticalHeader().show()
        self.view.setModel(self.model)
        self.view.hideColumn(0)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.newButton = self.buttonBox.addButton(m18nc('define a new player', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.slotInsert)
        self.deleteButton = self.buttonBox.addButton(m18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(self.buttonBox)
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

        self.setWindowTitle(m18n("Players") + ' - Kajongg')
        self.setObjectName('Players')

    def showEvent(self, dummyEvent):
        """adapt view to content"""
        if not self.model.select():
            logError("PlayerList: select failed")
            sys.exit(1)
        self.view.initView()
        StateSaver(self, self.view.horizontalHeader())
        if not self.view.isColumnHidden(2):
            # we loaded a kajonggrc written by an older kajongg version where this table
            # still had more columns. This should happen only once.
            self.view.hideColumn(2)
            self.view.hideColumn(3)

    def accept(self):
        """commit all modifications"""
        self.view.selectRow(0) # if ALT-O is entered while editing a new row, this is one way
        # to end editing and to pass the new value to the model
        if not self.model.submitAll():
            Sorry(m18n('Cannot save this. Possibly the name already exists. <br><br>' \
                    'Message from database:<br><br><message>%1</message>',
                    self.model.lastError().text()))
            return
        QDialog.accept(self)

    def slotInsert(self):
        """insert a record"""
        self.model.insertRow(self.model.rowCount())
        self.view.selectRow(self.model.rowCount()-1)

    def delete(self):
        """delete selected entries"""
        sel = self.view.selectionModel()
        maxDel = self.view.currentIndex().row() - 1
        for idx in sel.selectedIndexes():
            if idx.column() != 1:
                continue
            # sqlite3 does not enforce referential integrity.
            # we could add a trigger to sqlite3 but if it raises an exception
            # it will be thrown away silently.
            # if anybody knows how to propagate sqlite3 exceptions via QtSql
            # into python please tell me (wrohdewald)
            player = self.model.createIndex(idx.row(), 0).data().toInt()[0]
            # no query preparation, we don't expect lots of data
            if Query("select 1 from game where p0==%d or p1==%d or p2==%d or p3==%d" % \
                (player, player, player, player)).records:
                Sorry(m18n('This player cannot be deleted. There are games associated with %1.',
                        idx.data().toString()))
            else:
                self.model.removeRow(idx.row())
                maxDel = max(maxDel, idx.row())
        self.view.selectRow(maxDel+1)

    def keyPressEvent(self, event):
        """use insert/delete keys for insert/delete"""
        key = event.key()
        if key == Qt.Key_Insert:
            self.slotInsert()
            return
        QDialog.keyPressEvent(self, event)
Ejemplo n.º 52
0
class ReferenceDataDlg(QDialog):

    def __init__(self, table, title, parent=None):
        super(ReferenceDataDlg, self).__init__(parent)
        self.create_widgets(table)
        self.layout_widgets()
        self.create_connections()
        self.setWindowTitle(
                "Asset Manager - Edit {0} Reference Data".format(title))


    def create_widgets(self, table):
        self.model = QSqlTableModel(self)
        self.model.setTable(table)
        self.model.setSort(NAME, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.model.setHeaderData(NAME, Qt.Horizontal, QVariant("Name"))
        self.model.setHeaderData(DESCRIPTION, Qt.Horizontal,
                                 QVariant("Description"))
        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.addButton = QPushButton("&Add")
        self.deleteButton = QPushButton("&Delete")
        self.okButton = QPushButton("&OK")


    def layout_widgets(self):
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.addButton)
        buttonLayout.addWidget(self.deleteButton)
        buttonLayout.addStretch()
        buttonLayout.addWidget(self.okButton)
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)


    def create_connections(self):
        self.addButton.clicked.connect(self.addRecord)
        self.deleteButton.clicked.connect(self.deleteRecord)
        self.okButton.clicked.connect(self.accept)


    def addRecord(self):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row, NAME)
        self.view.setCurrentIndex(index)
        self.view.edit(index)


    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        
        record = self.model.record(index.row())
        id = record.value(ID).toInt()[0]
        table = self.model.tableName()
        query = QSqlQuery()
        if table == "deps":
            query.exec_(QString("SELECT COUNT(*) FROM employee "
                                "WHERE deo_id = %1").arg(id))
        elif table == "cities":
            query.exec_(QString("SELECT COUNT(*) FROM employee "
                                "WHERE city_id = %1").arg(id))
        count = 0
        if query.next():
            count = query.value(0).toInt()[0]
        if count:
            QMessageBox.information(self,
                    QString("Delete %1").arg(table),
                    (QString("Cannot delete %1<br>"
                             "from the %2 table because it is used by "
                             "%3 records")
                    .arg(record.value(NAME).toString())
                    .arg(table).arg(count)))
            
            return
        self.model.removeRow(index.row())
        self.model.submitAll()
Ejemplo n.º 53
0
class StaffDataDlg(QDialog):
    def __init__(self, parent=None):
        super(StaffDataDlg, self).__init__(parent)
        self.create_widgets()
        self.layout_widgets()
        self.create_connections()
        self.setMinimumWidth(850)
        self.setWindowTitle(u"Список сотрудников компании")

    def create_widgets(self):
        self.model = QSqlTableModel(self)
        self.model.setTable("employee")
        self.model.setSort(ID, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        self.model.setHeaderData(CITY, Qt.Horizontal, QVariant("City"))
        self.model.setHeaderData(DEPARTMENT, Qt.Horizontal, QVariant("Department"))
        self.model.setHeaderData(FIRSTNAME, Qt.Horizontal, QVariant("First Name"))
        self.model.setHeaderData(LASTNAME, Qt.Horizontal, QVariant("Last Name"))
        self.model.setHeaderData(SEX, Qt.Horizontal, QVariant("sex"))
        self.model.setHeaderData(ADDRESS, Qt.Horizontal, QVariant("Address"))
        self.model.setHeaderData(PID, Qt.Horizontal, QVariant("PID"))

        self.model.setHeaderData(TITLE, Qt.Horizontal, QVariant("Title"))

        self.model.setHeaderData(SOLARY, Qt.Horizontal, QVariant("SOLARY"))
        self.model.setHeaderData(SHIFT, Qt.Horizontal, QVariant("SHIFT"))
        self.model.setHeaderData(HOURS, Qt.Horizontal, QVariant("HOURS"))

        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.buttonBox = QDialogButtonBox()
        self.addButton = self.buttonBox.addButton(u"&Добавить", QDialogButtonBox.ActionRole)
        self.deleteButton = self.buttonBox.addButton(u"&Удалить", QDialogButtonBox.ActionRole)
        self.sortButton = self.buttonBox.addButton(u"&Сортировать", QDialogButtonBox.ActionRole)

        menu = QMenu(self)
        self.sortByTitleAction = menu.addAction(u"Сортировка по &Title")
        self.sortBySolaryAction = menu.addAction(u"Сортировка по &SOLARY")
        self.sortByIDAction = menu.addAction(u"Сортировка по &ID")
        self.sortButton.setMenu(menu)
        self.closeButton = self.buttonBox.addButton(QDialogButtonBox.Close)

    def layout_widgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def create_connections(self):
        self.addButton.clicked.connect(self.addRecord)
        self.deleteButton.clicked.connect(self.deleteRecord)

        self.closeButton.clicked.connect(self.accept)

    def addRecord(self):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row, TITLE)
        self.view.setCurrentIndex(index)
        self.view.edit(index)

    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        record = self.model.record(index.row())
        title = record.value(TITLE).toString()
        desc = record.value(SOLARY).toString()
        if (
            QMessageBox.question(
                self,
                "Reference Data",
                QString("Delete %1 from title %2?").arg(desc).arg(title),
                QMessageBox.Yes | QMessageBox.No,
            )
            == QMessageBox.No
        ):
            return
        self.model.removeRow(index.row())
        self.model.submitAll()
Ejemplo n.º 54
0
 def setData(self, index, value, role):
     if index.column() == 2 and role == Qt.CheckStateRole:
         return QSqlTableModel.setData(self, index, QVariant('1' if value == Qt.Checked else '0'), Qt.EditRole)
     return QSqlTableModel.setData(self, index, value, role)
Ejemplo n.º 55
0
 def __init__(self, parent=None, db=None):
     QSqlTableModel.__init__(self, parent, db)
     self.headers = [_('Addr'), _('Title'), u'', u'']
     self.font = QFont("Monospace", 18)
Ejemplo n.º 56
0
 def flags(self, index):
     flags = QSqlTableModel.flags(self, index)
     flags &= ~Qt.ItemIsEditable
     if index.column() == 2:
         flags |= Qt.ItemIsUserCheckable
     return flags
Ejemplo n.º 57
0
    def genTwoTab(self, tabtitle=""):
        # Create the tab title sytle.
        tabtitle = QLabel()
        tabtitle.setFont(QFont('Courier New', 20))
        tabtitle.setText("班级学生信息管理")
        tabtitle.setStyleSheet("border: 1px solid blue; color:rgba(0,0,255, 220);\
            background-color:rgba(201,201,201,60);\
            border-radius: 6px; \
            padding: 1px 18px 1px 20px;\
            min-width: 8em;")
        tabtitle.setMinimumHeight(50);
        titleLayout = QHBoxLayout()
        titleLayout.addWidget(tabtitle)
        titleLayout.setAlignment(tabtitle, Qt.AlignCenter)

       
        # Create the classnameView
        self.ClassnameView = QTableView()
        self.ClassnameModel = QSqlTableModel(self.ClassnameView)
        self.ClassnameModel.setTable("classtable")
        # self.ClassnameModel.setRelation(2, QSqlRelation("mentalmodel", "id", "name"));
        self.ClassnameModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.ClassnameModel.select()

        self.ClassnameModel.setHeaderData(0, Qt.Horizontal, "班级名称")

        # for indx, iheader in enumerate(["classid", "classname"]):
        #     self.ClassnameModel.setHeaderData(indx+1, Qt.Horizontal, iheader)
    
        self.ClassnameView.setModel(self.ClassnameModel)
        # self.ClassnameView.setColumnHidden(0, True)
        # self.ClassnameView.show()
        self.ClassnameView.verticalHeader().setFixedWidth(30)
        self.ClassnameView.verticalHeader().setStyleSheet("color: red;font-size:20px; ");
        self.ClassnameView.setStyleSheet("QTableView{background-color: rgb(250, 250, 200, 0);"  
                    "alternate-background-color: rgb(141, 163, 0);}"
                    "QTableView::item:hover {background-color: rgba(100,200,220,100);} ") 
        self.ClassnameView.setStyleSheet("font-size:16px; ");
        self.ClassnameView.setSelectionMode(QAbstractItemView.SingleSelection)
        # self.ClassnameView.dataChanged.connect(self.dataChanged)

        # self.ClassnameView.setSizePolicy(QSizePolicy.Expanding,     QSizePolicy.Expanding)

        # the second list
        self.StudentView = QTableView()
        self.StudentModel = QSqlTableModel(self.StudentView)
        self.StudentModel.setTable("student")
        # self.StudentModel.setRelation(2, QSqlRelation("mentalmodel", "id", "name"));
        self.StudentModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        # self.StudentModel.select()

        query = QSqlQuery(self.db)
        strwhere = " 1=1 "
        if self.g_curClassName == "":
            ret = query.exec_("select classname from classtable")
            query.next()
            firstClassName = query.value(0)
            strwhere += " and classname like '" + firstClassName + "'"
            
        self.StudentModel.setFilter(strwhere)
        self.StudentModel.select()

        for indx, iheader in enumerate(["班级名称", "学生编号", "学生姓名", "答对次数", "答错次数"]):
            self.StudentModel.setHeaderData(indx+1, Qt.Horizontal, iheader)
    
        self.StudentView.setModel(self.StudentModel)
        self.StudentView.setColumnHidden(0, True)

        # query = QSqlQuery(self.db)  
        lstClassName = []      
        query.exec_("select classname from classtable" ) 
        while(query.next()):
            lstClassName.append(query.value(0))

        self.StudentView.setItemDelegateForColumn(1,  ComboBoxDelegate(self, lstClassName, self.db))
        # self.StudentView.show()
        self.StudentView.verticalHeader().setFixedWidth(30)
        self.StudentView.verticalHeader().setStyleSheet("color: red;font-size:20px; background-color: rgb(250, 250, 200, 100)");
        self.StudentView.setStyleSheet("QTableView{background-color: rgb(250, 250, 200, 0);"  
                    "alternate-background-color: rgb(141, 163, 250);}"
                    "QTableView::item:hover {background-color: rgba(10,200,100,200);} "
                    ) 
        self.StudentView.setStyleSheet("font-size:16px;")
        self.StudentView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.StudentView.doubleClicked.connect(self.dbclick2)

        btn_lst1_layout = QGridLayout()
        newusrbtn       = QPushButton("新增")
        savebtn         = QPushButton("保存")
        revertbtn       = QPushButton("撤销")
        removebtn       = QPushButton("删除")
        btn_lst1_layout.addWidget(newusrbtn, 0, 0)
        btn_lst1_layout.addWidget(savebtn, 0, 1)
        btn_lst1_layout.addWidget(revertbtn, 1, 0)
        btn_lst1_layout.addWidget(removebtn, 1, 1)

        newusrbtn.clicked.connect(self.newClass)
        savebtn.clicked.connect(self.saveClass)
        revertbtn.clicked.connect(self.revertClass)
        removebtn.clicked.connect(self.removeClass)

        self.ClassnameView.doubleClicked.connect(self.dbclick)
        

        btnbox2 = QDialogButtonBox(Qt.Horizontal)
        newusrbtn2       = QPushButton("新增")
        savebtn2         = QPushButton("保存")
        revertbtn2       = QPushButton("撤销")
        removebtn2       = QPushButton("删除")
        btnbox2.addButton(newusrbtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(savebtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(revertbtn2, QDialogButtonBox.ActionRole);
        btnbox2.addButton(removebtn2, QDialogButtonBox.ActionRole);

        newusrbtn2.clicked.connect(self.newStudent)
        savebtn2.clicked.connect(self.saveStudent)
        revertbtn2.clicked.connect(self.revertStudent)
        removebtn2.clicked.connect(self.removeStudent)

        # left list layout
        lst_layout_1 = QVBoxLayout()
        lst_layout_1.addWidget(self.ClassnameView)
        lst_layout_1.addLayout(btn_lst1_layout)

        lst_layout_2 = QVBoxLayout()
        lst_layout_2.addWidget(self.StudentView)
        lst_layout_2.addWidget(btnbox2)
        
        lstlayout = QHBoxLayout()
        lstlayout.setMargin(5)
        # lstlayout.addLayout(findbox)
        lstlayout.addLayout(lst_layout_1, 2)
        lstlayout.setMargin(5)
        lstlayout.addLayout(lst_layout_2, 5)
            
        labelClass = QLabel("")
        labelClass.setStyleSheet("background-color:rgba(255, 255, 255,0); color:rgba(0,0,0,0);")
        labelClass.setFixedHeight(40)
        # labelClass.setFixedWidth(100)
        # labelClass.setFont(QFont('宋体', 10))

        bottomlayout = QHBoxLayout()        
        bottomlayout.addWidget(labelClass)        

        tab2layout = QVBoxLayout()
        tab2layout.addLayout(titleLayout)       
        tab2layout.addLayout(lstlayout)
        tab2layout.addLayout(bottomlayout)
        self.w2.setLayout(tab2layout)
        self.w2.setStyleSheet("background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff, stop: 1 #228888);")
Ejemplo n.º 58
0
    def workcat_fill_table(self, widget, table_name, hidde=False, set_edit_triggers=QTableView.NoEditTriggers, expr=None):
        """ Fill table @widget filtering query by @workcat_id
        Set a model with selected filter.
        Attach that model to selected table
        @setEditStrategy:
            0: OnFieldChange
            1: OnRowChange
            2: OnManualSubmit
        """

        # Set model
        model = QSqlTableModel()
        model.setTable(self.schema_name+"."+table_name)
        model.setEditStrategy(QSqlTableModel.OnFieldChange)
        model.setSort(0, 0)
        model.select()

        widget.setEditTriggers(set_edit_triggers)
        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())
        # Attach model to table view
        if expr:
            widget.setModel(model)
            widget.model().setFilter(expr)
        else:
            widget.setModel(model)

        if hidde:
            self.refresh_table(widget)
Ejemplo n.º 59
0
class MainForm(QDialog):
    def __init__(self):
        super(MainForm, self).__init__()

        self.model = QSqlTableModel(self)
        self.model.setTable('tbl_symbols')
        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        addButton = QPushButton("&Add")
        deleteButton = QPushButton("&Delete")

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(deleteButton)
        buttonLayout.addStretch()

        lay = QHBoxLayout()
        lay.addWidget(self.view)
        lay.addLayout(buttonLayout)
        self.setLayout(lay)

        self.connect(addButton, SIGNAL("clicked()"), self.addRecord)
        self.connect(deleteButton, SIGNAL("clicked()"), self.deleteRecord)

    def addRecord(self):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row, 1)
        self.view.setCurrentIndex(index)
        self.view.edit(index)

    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        #QSqlDatabase.database().transaction()
        record = self.model.record(index.row())
        self.model.removeRow(index.row())
        self.model.submitAll()
    def fill_table(self, widget, table_name, hidde=False, set_edit_triggers=QTableView.NoEditTriggers, expr=None ):
        """ Set a model with selected filter.
        Attach that model to selected table
        @setEditStrategy:
            0: OnFieldChange
            1: OnRowChange
            2: OnManualSubmit
        """

        # Set model
        model = QSqlTableModel()
        model.setTable(self.schema_name+"."+table_name)
        model.setEditStrategy(QSqlTableModel.OnFieldChange)
        model.setSort(0, 0)
        model.select()

        # When change some field we need to refresh Qtableview and filter by psector_id
        model.dataChanged.connect(partial(self.refresh_table, widget))
        model.dataChanged.connect(partial(self.update_total, widget))
        widget.setEditTriggers(set_edit_triggers)
        # Check for errors
        if model.lastError().isValid():
            self.controller.show_warning(model.lastError().text())
        # Attach model to table view
        if expr:
            widget.setModel(model)
            widget.model().setFilter(expr)
        else:
            widget.setModel(model)

        if hidde:
            self.refresh_table(widget)