填充组合框可编辑用户名和行编辑密码

填充组合框可编辑用户名和行编辑密码

本文介绍了从 sqlite3 填充组合框可编辑用户名和行编辑密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 1 个组合框可编辑用户名和 1 个行编辑密码,我想将用户列表从数据库 sqlite3 加载到组合框.加载列表后,我想对 itemlist 组合框进行操作,从数据库中获取当前选定用户的密码.

I have 1 combobox editable username and 1 line edit password i want load user list from database sqlite3 to combobox. After load list i want action on itemlist combobox get password current selected user from database.

pyqt5 应用

表格列

表记录

######Combo Box 2 - PM's
        self.groupBox_2 = QtWidgets.QGroupBox(self.tab)
        self.groupBox_2.setGeometry(QtCore.QRect(10, 140, 191, 51))
        self.groupBox_2.setObjectName("groupBox_2")
        self.comboBox_3 = QtWidgets.QComboBox(self.groupBox_2)
        self.comboBox_3.setGeometry(QtCore.QRect(10, 20, 171, 22))
        self.comboBox_3.setObjectName("comboBox_3")
        self.comboBox_3.addItems(self.pm_Combo)

def pm_Combo(self):
        conn = sqlite3.connect('testdb.db')
        c = conn.cursor()
        c.execute("SELECT DISTINCT projectmanager FROM testtable2")
        pmList = c.fetchall()
        conn.commit()
        conn.close()

推荐答案

假设表名为user",那么可以使用 userData 来保存信息,并在 QComboBox 的 currentIndex 更改时将其设置在 QLineEdit 中:

Assuming that the table is called "user" then you can use the userData to save the information and set it in the QLineEdit when the currentIndex of the QComboBox changes:

import os
import sqlite3
import sys

from PyQt5 import QtWidgets, QtSql


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.username_combo = QtWidgets.QComboBox()
        self.password_lineedit = QtWidgets.QLineEdit()

        button_login = QtWidgets.QPushButton(self.tr("Login"))

        lay = QtWidgets.QFormLayout(self)
        lay.addRow(self.tr("Username:"), self.username_combo)
        lay.addRow(self.tr("Password:"), self.password_lineedit)
        lay.addRow(button_login)

        self.username_combo.currentIndexChanged.connect(self.update_password)

        self.load_usernames()

    def load_usernames(self):
        current_dir = os.path.dirname(os.path.realpath(__file__))
        db_path = os.path.join(current_dir, "testdb.db")

        self.username_combo.clear()
        with sqlite3.connect(db_path) as conn:
            cursor = conn.execute("SELECT DISTINCT username, password FROM User")
            for result in cursor.fetchall():
                username, password = result
                self.username_combo.addItem(username, password)

    def update_password(self):
        self.password_lineedit.setText(self.username_combo.currentData())


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

另一种可能的解决方案是将 QSqlQueryModel 与 QDataWidgetMapper 结合使用:

Another possible solution is to use QSqlQueryModel with QDataWidgetMapper:

import os
import sys

from PyQt5 import QtWidgets, QtSql


def create_connection():
    current_dir = os.path.dirname(os.path.realpath(__file__))
    db_path = os.path.join(current_dir, "testdb.db")

    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(db_path)
    if not db.open():
        print("error: {}".format(db.lastError().text()))
        return False
    return True


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.username_combo = QtWidgets.QComboBox()
        self.password_lineedit = QtWidgets.QLineEdit()

        button_login = QtWidgets.QPushButton(self.tr("Login"))

        lay = QtWidgets.QFormLayout(self)
        lay.addRow(self.tr("Username:"), self.username_combo)
        lay.addRow(self.tr("Password:"), self.password_lineedit)
        lay.addRow(button_login)
        self.load_data()

    def load_data(self):
        self.model = QtSql.QSqlQueryModel()
        self.model.setQuery("""SELECT DISTINCT username, password FROM User""")
        self.mapper = QtWidgets.QDataWidgetMapper()
        self.mapper.setModel(self.model)
        self.mapper.addMapping(self.password_lineedit, 1)
        self.username_combo.currentIndexChanged.connect(self.mapper.setCurrentIndex)
        self.username_combo.setModel(self.model)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    if not create_connection():
        sys.exit(-1)

    w = Widget()
    w.show()

    sys.exit(app.exec_())

这篇关于从 sqlite3 填充组合框可编辑用户名和行编辑密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 17:39