05
Май
2021

Как мне получить данные той строки в которой нажимается кнопка?

Main.py

from PyQt5 import QtCore, QtGui, QtWidgets
from setings_ip import *
from PyQt5.Qt import *
import sqlite3

class InputCorporateDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Input Dialog')

        self.line_edit_ip = QLineEdit()
        self.line_edit_corporate = QLineEdit()
        self.line_edit_street = QLineEdit()
        self.line_edit_city = QLineEdit()

        form_layout = QFormLayout()
        form_layout.addRow('IP:', self.line_edit_ip)
        form_layout.addRow('Организация:', self.line_edit_corporate)
        form_layout.addRow('Улица:', self.line_edit_street)
        form_layout.addRow('Город:', self.line_edit_city)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

        main_layout = QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addWidget(button_box)
        self.setLayout(main_layout)
        

class Widget(QtWidgets.QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(0)
        
        self.pushButton.clicked.connect(self.add_new_row)
        
        self.row_count = 1
        self.table_index = 0

        sqlite_connection = sqlite3.connect("New.db")
        cursor = sqlite_connection.cursor()

        sqlite_select_query = """SELECT ip, Location, Yi, Gor FROM ips"""
        cursor.execute(sqlite_select_query)
        records = cursor.fetchall()

        
        
        for row in records:
            clear_button = QPushButton("Удалить", self)
            clear_button.setStyleSheet("QPushButton {\n"
            "    background-color: #fa7f72;\n"
            "}\n"
            "QPushButton:hover {\n"
            "    background-color: white;\n"
            "}\n"
            "QPushButton:pressed {\n"
            "    color: #626AB0;\n"
            "    background-color: #D5D4D4;\n"
            "}")

            edit_button = QPushButton("Изменить", self)
            edit_button.setStyleSheet("QPushButton {\n"
            "    background-color: #00b8ef;\n"
            "}\n"
            "QPushButton:hover {\n"
            "    background-color: white;\n"
            "}\n"
            "QPushButton:pressed {\n"
            "    color: #626AB0;\n"
            "    background-color: #D5D4D4;\n"
            "}")

            self.tableWidget.setRowCount(self.row_count)
            self.tableWidget.setCellWidget(self.table_index, 0, clear_button)
            self.tableWidget.setCellWidget(self.table_index, 1, edit_button)
            self.tableWidget.setItem(self.table_index, 2, QtWidgets.QTableWidgetItem(str(row[0])))
            self.tableWidget.setItem(self.table_index, 3, QtWidgets.QTableWidgetItem(str(row[1])))
            self.tableWidget.setItem(self.table_index, 4, QtWidgets.QTableWidgetItem(str(row[2])))
            self.tableWidget.setItem(self.table_index, 5, QtWidgets.QTableWidgetItem(str(row[3])))

            self.table_index += 1
            self.row_count += 1

        cursor.close()
        sqlite_connection.close()
       
    def add_new_row(self):
        inputDialog = InputCorporateDialog()
        rez = inputDialog.exec()
        if not rez:
            msg = QMessageBox.information(self, 'Внимание', 'Диалог сброшен.')
            return
        
        text = inputDialog.line_edit_ip.text()
        text1 = inputDialog.line_edit_corporate.text()
        text2 = inputDialog.line_edit_street.text()
        text3 = inputDialog.line_edit_city.text()
        rowPosition = self.tableWidget.rowCount()

        if text and text1 and text2 and text3:        
            self.tableWidget.insertRow(rowPosition)
            self.tableWidget.setItem(rowPosition , 0, QtWidgets.QTableWidgetItem(text))
            self.tableWidget.setItem(rowPosition , 1, QtWidgets.QTableWidgetItem(text1))
            self.tableWidget.setItem(rowPosition , 2, QtWidgets.QTableWidgetItem(text2))
            self.tableWidget.setItem(rowPosition , 3, QtWidgets.QTableWidgetItem(text3))

            connect = sqlite3.connect("New.db")
            cursor = connect.cursor()

            texts = [(text3, text2, text1, text)]

            cursor.executemany("INSERT INTO ips VALUES(?, ?, ?, ?);", texts)
            connect.commit()
            cursor.close()

        else:
            msg = QMessageBox.information(self, 'Внимание', 'Заполните все поля.')

    def clear_item(self):
        pass

    def edit_item(self):
        pass


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(450, 200)
    w.show()
    sys.exit(app.exec_())

setings_ip.py

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(606, 334)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/ico/Python.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        self.gridLayout = QtWidgets.QGridLayout(Form)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setStyleSheet("QPushButton {\n"
"    background-color: #54e346;\n"
"}\n"
"QPushButton:hover {\n"
"    background-color: white;\n"
"}\n"
"QPushButton:pressed {\n"
"    color: #626AB0;\n"
"    background-color: #D5D4D4;\n"
"}")
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(6)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        self.gridLayout.addWidget(self.tableWidget, 1, 0, 1, 1)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Настройка ip"))
        self.pushButton.setText(_translate("Form", "Добавить"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("Form", "ip"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("Form", "Организация"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("Form", "Улица"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("Form", "Город"))
#import res_rc

Бд

import sqlite3

# Добавление данных в таблицы

try:
    connect = sqlite3.connect("News.db")
    cursor = connect.cursor()
    print("База данных подключена к SQLite")
    
    cursor.execute("""CREATE TABLE IF NOT EXISTS ips(
                      ip INTEGER,
                      Gor TEXT,
                      Yi TEXT,
                      Location TEXT);""")

    connect.commit()

    records = [[f"192.168.{i}.9", "None", "None", "None"] for i in range(1, 101)]
    cursor.executemany("INSERT INTO ips VALUES (?, ?, ?, ?)", records)
    connect.commit()

    print("Запись успешно добавлена")
    cursor.close()

except sqlite3.Error as error:
    print("Ошибка при работе с SQLite", error)

finally:
    if connect:
        connect.close()
        print("Соединение с SQLite закрыто")

Источник: https://ru.stackoverflow.com/questions/1278274/%D0%9A%D0%B0%D0%BA-%D0%BC%D0%BD%D0%B5-%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D0%B5-%D1%82%D0%BE%D0%B9-%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8-%D0%B2-%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D0%BE%D0%B9-%D0%BD%D0%B0%D0%B6%D0%B8%D0%BC%D0%B0%D0%B5%D1%82%D1%81%D1%8F-%D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D0%B0

Тебе может это понравится...

Добавить комментарий