当前位置: 首页>>代码示例>>Python>>正文


Python QSqlTableModel.index方法代码示例

本文整理汇总了Python中PyQt4.QtSql.QSqlTableModel.index方法的典型用法代码示例。如果您正苦于以下问题:Python QSqlTableModel.index方法的具体用法?Python QSqlTableModel.index怎么用?Python QSqlTableModel.index使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtSql.QSqlTableModel的用法示例。


在下文中一共展示了QSqlTableModel.index方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MainForm

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]
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()    
开发者ID:Artemis1997,项目名称:trading-with-python,代码行数:46,代码来源:guiWithDatabase.py

示例2: ReferenceDataDlg

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]
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()
开发者ID:janusnic,项目名称:21v-python,代码行数:91,代码来源:main4.py

示例3: StaffDataDlg

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]
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()
开发者ID:janusnic,项目名称:21v-python,代码行数:89,代码来源:main.py

示例4: MainWindow

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]

#.........这里部分代码省略.........

    def setupTables(self):
        """
            Initialize all the application tablesview
        """
        self.cTableView.setModel(self.cModel)
        self.cTableView.setItemDelegate(MyQSqlRelationalDelegate(self))
        self.cTableView.setColumnHidden(CID, True)
        self.cTableView.setWordWrap(True)
        self.cTableView.resizeRowsToContents()
        self.cTableView.setAlternatingRowColors(True)
        self.cItmSelModel = QItemSelectionModel(self.cModel)
        self.cTableView.setSelectionModel(self.cItmSelModel)
        self.cTableView.setSelectionBehavior(QTableView.SelectRows)
        self.cTableView.setSortingEnabled(True)

    def updateFilter(self):
        self.cModel.select()
        self.cTableView.setColumnHidden(CID, True)

    def applyFilter(self):
        if not self.db.isOpen():
            self.statusbar.showMessage(
                "Database non aperto...",
                5000)
            return
        filter = (  "ragsoc LIKE '%s' OR "
                    "indirizzo LIKE '%s' OR "
                    "note LIKE '%s'" %
                    ((self.filterLineEdit.text(),)*3))
        self.cModel.setFilter(filter)
        self.filtered = True
        self.updateFilter()

    def resetFilter(self):
        if not self.db.isOpen():
            self.statusbar.showMessage(
                "Database non aperto...",
                5000)
            return
        self.filtered = False
        self.filterLineEdit.setText("")
        self.cModel.setFilter("")
        self.updateFilter()

    def addCliRecord(self):
        if not self.db.isOpen():
            self.statusbar.showMessage(
                "Database non aperto...",
                5000)
            return
        customerIndex = self.cTableView.currentIndex()
        if self.filtered:
            self.resetFilter()
        self.cModel.submitAll()
        self.cModel.select()
        row = self.cModel.rowCount()
        self.cModel.insertRow(row)
        self.editindex = self.cModel.index(row, CRAGSOC)
        self.cTableView.setCurrentIndex(self.editindex)
        self.cTableView.edit(self.editindex)

    def delCliRecord(self):
        if not self.db.isOpen():
            self.statusbar.showMessage(
                "Database non aperto...",
                5000)
            return
        selrows = self.cItmSelModel.selectedRows()
        if not selrows:
            self.statusbar.showMessage(
                "No selected customers to delete...",
                5000)
            return
        if(QMessageBox.question(self, "Delete Customers",
                "Do you want to delete: {0} customer(s)?".format(len(selrows)),
                QMessageBox.Yes|QMessageBox.No) ==
                QMessageBox.No):
            return
        QSqlDatabase.database().transaction()
        query = QSqlQuery()
        query.prepare("DELETE FROM clienti WHERE id = :val")
        for i in selrows:
            if i.isValid():
                query.bindValue(":val", QVariant(i.data().toInt()[0]))
                query.exec_()
        QSqlDatabase.database().commit()
        self.cModel.select()

    def setupUiSignals(self):
        self.connect(self.addPushButton, SIGNAL("clicked()"),
                    self.addCliRecord)
        self.connect(self.delPushButton, SIGNAL("clicked()"),
                    self.delCliRecord)
        self.connect(self.filterPushButton, SIGNAL("clicked()"),
                    self.applyFilter)
        self.connect(self.resetPushButton, SIGNAL("clicked()"),
                    self.resetFilter)
        self.connect(self.filterLineEdit, SIGNAL("returnPressed()"),
                    self.applyFilter)
开发者ID:L0cutus,项目名称:Gestione-Clienti,代码行数:104,代码来源:clienti.py

示例5: DataDialog

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]
class DataDialog(QDialog):
    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)

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

    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        self.model.removeRow(index.row())
        self.model.submitAll()

    def accept(self):
        QDialog.accept(self)
开发者ID:jedamus,项目名称:vim-python,代码行数:69,代码来源:edit_mysql_vim.py

示例6: MainWindow

# 需要导入模块: from PyQt4.QtSql import QSqlTableModel [as 别名]
# 或者: from PyQt4.QtSql.QSqlTableModel import index [as 别名]
class MainWindow(QMainWindow, magazzino_ui.Ui_MainWindow):

    FIRST, PREV, NEXT, LAST = range(4)
    Clipboard = [] # lista di oggetti

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)
        self.setupMenu()
        self.restoreWinSettings()

        self.editindex = None
        self.filename = None
        self.db = QSqlDatabase.addDatabase("QSQLITE")

        self.loadInitialFile()
        self.setupUiSignals()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Down:
            self.addDettRecord()
        else:
            QMainWindow.keyPressEvent(self, event)

    def creaStrutturaDB(self):
        query = QSqlQuery()
        if not ("magamaster" in self.db.tables()):
            if not query.exec_("""CREATE TABLE magamaster (
                                id INTEGER PRIMARY KEY AUTOINCREMENT 
                                UNIQUE NOT NULL,
                                scaff VARCHAR(10) NOT NULL)"""):
                QMessageBox.warning(self, "Magazzino",
                                QString("Creazione tabella fallita!"))
                return False

        if not ("magaslave" in self.db.tables()):
            if not query.exec_("""CREATE TABLE magaslave (
                                id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
                                datains DATE NOT NULL,
                                abbi VARCHAR(50),
                                angro VARCHAR(50),
                                desc VARCHAR(100),
                                qt INTEGER NOT NULL DEFAULT '1',
                                imp DOUBLE NOT NULL DEFAULT '0.0',
                                equiv VARCHAR(100),
                                mmid INTEGER NOT NULL,
                                fatt VARCHAR(50),
                                note VARCHAR(200),
                                FOREIGN KEY (mmid) REFERENCES magamaster)"""):
                QMessageBox.warning(self, "Magazzino",
                                QString("Creazione tabella fallita!"))
                return False
            QMessageBox.information(self, "Magazzino",
                                QString("Database Creato!"))

        return True

    def loadFile(self, fname=None):
        if fname is None:
            return
        if self.db.isOpen():
            self.db.close()
        self.db.setDatabaseName(QString(fname))
        if not self.db.open():
            QMessageBox.warning(self, "Magazzino",
                                QString("Database Error: %1")
                                .arg(self.db.lastError().text()))
        else:
            if not self.creaStrutturaDB():
                return
            self.filename = unicode(fname)
            self.setWindowTitle("Gestione Magazzino - %s" % self.filename)
            self.setupModels()
            self.setupMappers()
            self.setupTables()
            #self.setupItmSignals()
            self.restoreTablesSettings()
            self.mmUpdate()


    def loadInitialFile(self):
        settings = QSettings()
        fname = unicode(settings.value("Settings/lastFile").toString())
        if fname and QFile.exists(fname):
            self.loadFile(fname)


    def openFile(self):
        dir = os.path.dirname(self.filename) \
                if self.filename is not None else "."
        fname = QFileDialog.getOpenFileName(self,
                    "Gestione Magazzino - Scegli database",
                    dir, "*.db")
        if fname:
            self.loadFile(fname)


    def newFile(self):
        dir = os.path.dirname(self.filename) \
#.........这里部分代码省略.........
开发者ID:L0cutus,项目名称:Gestione-Magazzino,代码行数:103,代码来源:magazzino.py


注:本文中的PyQt4.QtSql.QSqlTableModel.index方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。