Esempio n. 1
0
    def start_game(self):
        para = self.merkozesek.currentItem().text().rsplit("\t")
        p1_model = QSqlQueryModel()
        p1_query = QSqlQuery(
            f"select player_id from torna_resztvevok where player_name='{para[2]}'"
        )
        p1_model.setQuery(p1_query)
        p2_model = QSqlQueryModel()
        p2_query = QSqlQuery(
            f"select player_id from torna_resztvevok where player_name='{para[3]}'"
        )
        p2_model.setQuery(p2_query)

        params = []
        params.append(para[2])
        params.append(para[3])
        params.append(int(para[0]))
        self.match_id = int(para[0])
        params.append(int(p1_model.record(0).value(0)))
        params.append(int(p2_model.record(0).value(0)))
        params.append(para[4])
        params.append(int(para[6]))
        params.append(int(para[5]))
        params.append(0)  # hc1
        params.append(0)  # hc2
        params.append(0)  #bets_of...
        self.parent.new_game_window.params = params
        self.parent.new_game_window.refresh()
Esempio n. 2
0
 def get_player_name(self):
     player_name_model = QSqlQueryModel()
     query = QSqlQuery(
         "SELECT player_name  FROM players order by player_name", db=db)
     player_name_model.setQuery(query)
     self.player1_completer.setModel(player_name_model)
     self.player2_completer.setModel(player_name_model)
Esempio n. 3
0
 def get_kedvezmenyezettdata(self):
     kedvezm_model = QSqlQueryModel()
     query = QSqlQuery(
         "SELECT megnevezes FROM kedvezmenyezettek order by megnevezes",
         db=db)
     kedvezm_model.setQuery(query)
     self.kedvezmenyezett_completer.setModel(kedvezm_model)
Esempio n. 4
0
    def accept(self):
        if self.uj_station:
            now = QDateTime.currentDateTime()
            network = QSqlTableModel()
            network.setTable("reged_station")
            rec_net = network.record()
            rec_net.remove(0)
            rec_net.setValue(0, self.station.text())
            rec_net.setValue(1, self.ip.text())
            rec_net.setValue(2, self.token.text())
            rec_net.setValue(3, now)
            if network.insertRecord(-1, rec_net):
                network.submitAll()
            else:
                db.rollback()
            self.uj_station = False

        if self.valtozott:
            # Módosítani a db-t és a config.ini-t
            # config.ini update
            config.set('DEFAULT', 'secret key', self.token.text())
            config.set('DEFAULT', 'station ip', self.ip.text())
            config.set('DEFAULT', 'station id', self.station.text())
            with open('config.ini', 'w') as configfile:
                config.write(configfile)
            # db update
            now = QDateTime.currentDateTime().toString(
                "yyyy-MM-ddThh:mm:ss.sss")
            model3 = QSqlQueryModel()
            query3 = QSqlQuery(
                f"update reged_station set station_id='{self.station.text()}', station_ip='{self.ip.text()}', timestamp='{now}' where secret_key='{self.token.text()}'",
                db=db)
            model3.setQuery(query3)
            self.valtozott = False
        super().accept()
Esempio n. 5
0
    def build(model_type='select'):
        # Дополнительный путь к SQL драйверу
        QApplication.setLibraryPaths(['./platforms', './plugins'])

        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('db25.db3')

        if not db.open():
            print('БД не существует')
            sys.exit(-1)

        if model_type == 'query':
            return QSqlQueryModel(), db
        else:
            model = MyTableModel(None, db)

        # model = MyTableModel(None, db, model_type)

        if 'mytable' not in db.tables():
            query = QSqlQuery()
            query.exec_(
                "create table mytable(id text primary key, title text, podsborka text, izdelie text)")

        model.setTable('mytable')
        model.setEditStrategy(QSqlTableModel.OnFieldChange)

        model.select()
        model.setHeaderData(0, Qt.Horizontal, "id")
        model.setHeaderData(1, Qt.Horizontal, "title")
        model.setHeaderData(2, Qt.Horizontal, "podsborka")
        model.setHeaderData(3, Qt.Horizontal, "izdelie")

        return model
Esempio n. 6
0
 def get_player_name(self):
     player_name_model = QSqlQueryModel()
     query = QSqlQuery(
         "SELECT player_name  FROM players where type='local' and aktiv=1 order by player_name",
         db=db)
     player_name_model.setQuery(query)
     self.player1_completer.setModel(player_name_model)
     self.player2_completer.setModel(player_name_model)
Esempio n. 7
0
 def load_saved_players(self):
     players = QSqlQueryModel()
     players_query = QSqlQuery("select * from players where aktiv=1")
     players.setQuery(players_query)
     self.saved_players.clear()
     for i in range(players.rowCount()):
         item = QListWidgetItem(players.record(i).value(1))
         item.setData(Qt.UserRole, players.record(i).value(0))
         self.saved_players.addItem(item)
Esempio n. 8
0
 def load_torna(self):
     torna = QSqlQueryModel()
     query = QSqlQuery("select * from torna_settings where aktiv=2")
     torna.setQuery(query)
     if torna.record(0).value(0):
         for i in range(torna.rowCount()):
             self.tournaments.addItem(
                 torna.record(i).value(1),
                 torna.record(i).value(0))  # a value(0) a torna_id
Esempio n. 9
0
 def selectModel(self):
     conn = self.db.getConnection()
     model = QSqlQueryModel()
     query = QSqlQuery(conn)
     self.buildSqlStatement(query)
     query.exec_()
     if query.lastError().driverText():
         print("Query error msg:", query.lastError().driverText())
     model.setQuery(query)
     self.ui.tblStats.setModel(model)
     self.ui.tblStats.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
Esempio n. 10
0
 def torna_valasztas(self, i):
     self.torna_id = self.tournaments.itemData(i)
     players = QSqlQueryModel()
     players_query = QSqlQuery(
         f"select * from torna_resztvevok where torna_id={self.torna_id}")
     players.setQuery(players_query)
     self.current_players.clear()
     for i in range(players.rowCount()):
         item = QListWidgetItem(players.record(i).value(1))
         item.setData(Qt.UserRole, players.record(i).value(0))
         self.current_players.addItem(item)
Esempio n. 11
0
 def load_torna_players(self):
     players = QSqlQueryModel()
     players_query = QSqlQuery(
         "select * from torna_resztvevok where 1 group by player_id, player_name"
     )
     players.setQuery(players_query)
     self.torna_players.clear()
     for i in range(players.rowCount()):
         item = QListWidgetItem(players.record(i).value(1))
         item.setData(Qt.UserRole, players.record(i).value(0))
         self.torna_players.addItem(item)
Esempio n. 12
0
    def stat_game(self):
        # Az átvett adatok:
        para = self.merkozesek.currentItem().text().rsplit("\t")
        # Összegyűjtjük egy listába a szükséges infókat
        self.get_adatok(para)
        self.szumma.change_data(self.adatok)
        for x in reversed(range(self.history_layout.count())):
            self.history_layout.itemAt(x).widget().deleteLater()
        # kiszedjük az adott meccs összes set és leg esetére a dobásokat
        sor = 0
        for s in range(1, self.adatok[8] + 1):
            # s: a set-ek száma
            if self.adatok[8] != 1:
                self.history_layout.addWidget(QLabel("Set: " + str(s)), sor, 0, 1, 2)
                sor += 1
            for l in range(1, self.adatok[7][s-1] + 1):
                sl1_model = QSqlQueryModel()
                p1_data_list = []
                p1_data_list.append(self.adatok[4])   # start_score1
                sl1_query = QSqlQuery(f"select * from dobas where match_id ={self.adatok[6]} and set_id={s} and leg_id={l} and player_id='{self.adatok[0]}'", db=db)
                sl1_model.setQuery(sl1_query)
                for i in range(sl1_model.rowCount()):
                    # Itt a model már tartalmazza a p1 összes dobását az adott leg-ben.
                    p1_data_row = []
                    p1_data_row.append(sl1_model.record(i).value(1))
                    p1_data_row.append(sl1_model.record(i).value(2))
                    p1_data_list.append(p1_data_row)
                self.history_layout.addWidget(PlayerLegWidget(self, p1_data_list), sor, 0, Qt.AlignTop)

                sl2_model = QSqlQueryModel()
                p2_data_list = []
                p2_data_list.append(self.adatok[5])  # start_score2
                sl2_query = QSqlQuery(f"select * from dobas where match_id ={self.adatok[6]} and set_id={s} and leg_id={l} and player_id='{self.adatok[2]}'", db=db)
                sl2_model.setQuery(sl2_query)
                for j in range(sl2_model.rowCount()):
                    p2_data_row = []
                    p2_data_row.append(sl2_model.record(j).value(1))
                    p2_data_row.append(sl2_model.record(j).value(2))
                    p2_data_list.append(p2_data_row)
                self.history_layout.addWidget(PlayerLegWidget(self, p2_data_list), sor, 1, Qt.AlignTop)
                sor += 1
Esempio n. 13
0
 def setLogs(self):
     isLogChanged = self.settings.value('logChanged')
     if isLogChanged == 1 or self.initialRun:
         self.allLogsModel = QSqlQueryModel()
         dbAllLog = QSqlDatabase.addDatabase("QSQLITE")
         dbAllLog.setDatabaseName("caio.db")
         dbAllLog.open()
         self.allLogsModel.setQuery(
             "select * from allLogs order by id desc ", dbAllLog)
         dbAllLog.close()
         print(self.allLogsModel)
         self.settings.setValue('logChanged', 0)
         QSqlDatabase.removeDatabase("QSQLITE")
         self.initialRun = False
    def __init__(self):
        super().__init__()

        self.table = QTableView()

        self.model = QSqlQueryModel()
        self.table.setModel(self.model)

        query = QSqlQuery("SELECT Name, Composer FROM track ", db=db)

        self.model.setQuery(query)

        self.setMinimumSize(QSize(1024, 600))
        self.setCentralWidget(self.table)
Esempio n. 15
0
    def jogcim_selected(self):
        napidij_model = QSqlQueryModel()
        query = QSqlQuery(
            "SELECT kulcs, ertek FROM settings WHERE kulcs LIKE '%napidij%'")
        napidij_model.setQuery(query)

        for i in range(napidij_model.rowCount()):
            if (napidij_model.record(i).value(0)
                    == 'ar_ifjusagi_napidij') and (self.jogcim.text()
                                                   == 'Ifjúsági napidíj'):
                self.osszeg.setText(str(napidij_model.record(i).value(1)))
            if (napidij_model.record(i).value(0)
                    == 'ar_napidij') and (self.jogcim.text() == 'Napidíj'):
                self.osszeg.setText(str(napidij_model.record(i).value(1)))
Esempio n. 16
0
    def change_data(self, szum=None):
        self.data = None
        self.data = szum
        self.name1 = self.data[1]
        self.name2 = self.data[3]
        match_id = self.data[6]
        p1_id = self.data[0]
        p2_id = self.data[2]
        # Végeredmény
        self.won1 = 0
        self.won2 = 0
        self.avg1 = self.avg2 = 0
        eredmenyek_model = QSqlQueryModel()
        eredmenyek_query = QSqlQuery(f"select * from matches where match_id={match_id}", db=db)
        eredmenyek_model.setQuery(eredmenyek_query)
        for x in range(1, self.data[8] + 1):
            l1 = l2 = 0
            for i in range(eredmenyek_model.rowCount()):  # csak set-eket összesítünk
                if eredmenyek_model.record(i).value(2) == x:
                    if eredmenyek_model.record(i).value(3) == p1_id:
                        l1 += 1
                    else:
                        l2 += 1
            # print("Set: ", x, "L1: ", l1, "L2: ", l2)
            if self.data[8] == 1:
                self.won1 = l1
                self.won2 = l2
            else:
                if l1 > l2:
                    self.won1 += 1
                else:
                    self.won2 += 1
        # Átlagok
        db1 = db2 = sum1 = sum2 = 0
        for x in range(1, self.data[8] + 1):
            for leg in range(1, self.data[7][x - 1] + 1):
                query = QSqlQuery(f"select max(round_number) as maxround, sum(points) as sumpont from dobas where leg_id={leg} and set_id={x} and match_id={match_id} and player_id={p1_id}")
                query.exec_()
                while query.next():
                    db1 += query.value(0)
                    sum1 += query.value(1)
                query2 = QSqlQuery(f"select max(round_number) as maxround, sum(points) as sumpont from dobas where leg_id={leg} and set_id={x} and match_id={match_id} and player_id={p2_id}")
                query2.exec_()
                while query2.next():
                    db2 += query2.value(0)
                    sum2 += query2.value(1)
        self.avg1 = round(sum1 / db1 * 3, 2)
        self.avg2 = round(sum2 / db2 * 3, 2)

        self.update()
    def __init__(self):
        super().__init__()

        container = QWidget()
        layout_search = QHBoxLayout()

        self.track = QLineEdit()
        self.track.setPlaceholderText("Track name...")
        self.track.textChanged.connect(self.update_query)

        self.composer = QLineEdit()
        self.composer.setPlaceholderText("Artist name...")
        self.composer.textChanged.connect(self.update_query)

        self.album = QLineEdit()
        self.album.setPlaceholderText("Album name...")
        self.album.textChanged.connect(self.update_query)

        layout_search.addWidget(self.track)
        layout_search.addWidget(self.composer)
        layout_search.addWidget(self.album)

        layout_view = QVBoxLayout()
        layout_view.addLayout(layout_search)

        self.table = QTableView()

        layout_view.addWidget(self.table)

        container.setLayout(layout_view)

        self.model = QSqlQueryModel()
        self.table.setModel(self.model)

        self.query = QSqlQuery(db=db)

        self.query.prepare(
            "SELECT Name, Composer, Album.Title FROM Track "
            "INNER JOIN Album ON Track.AlbumId=Album.AlbumId WHERE "
            "Track.Name LIKE '%' || :track_name || '%' AND "
            "Track.Composer LIKE '%' || :track_composer || '%' AND "
            "Album.Title LIKE '%' || :album_title || '%'"
        )

        self.update_query()

        self.setMinimumSize(QSize(1024, 600))
        self.setCentralWidget(container)
Esempio n. 18
0
    def jogcim_selected(self):
        berlet_model = QSqlQueryModel()
        query = QSqlQuery(
            "SELECT kulcs, ertek FROM settings WHERE kulcs LIKE '%berlet%'")
        berlet_model.setQuery(query)

        for i in range(berlet_model.rowCount()):
            if (berlet_model.record(i).value(0)
                    == 'ar_gyermek_berlet') and (self.jogcim.text()
                                                 == 'Gyermek bérlet'):
                self.osszeg.setText(str(berlet_model.record(i).value(1)))
            if (berlet_model.record(i).value(0)
                    == 'ar_ifjusagi_berlet') and (self.jogcim.text()
                                                  == 'Ifjúsági bérlet'):
                self.osszeg.setText(str(berlet_model.record(i).value(1)))
            if (berlet_model.record(i).value(0)
                    == 'ar_berlet') and (self.jogcim.text() == 'Bérlet'):
                self.osszeg.setText(str(berlet_model.record(i).value(1)))
Esempio n. 19
0
    def __init__(self):
        super().__init__()

        self.table = QTableView()

        self.model = QSqlQueryModel()
        self.table.setModel(self.model)

        query = QSqlQuery(db=db)
        query.prepare("SELECT Name, Composer, Album.Title FROM Track "
                      "INNER JOIN Album ON Track.AlbumId = Album.AlbumId "
                      "WHERE Album.Title LIKE '%' || :album_title || '%' ")
        query.bindValue(":album_title", "Sinatra")
        query.exec_()

        self.model.setQuery(query)
        self.setMinimumSize(QSize(1024, 600))
        self.setCentralWidget(self.table)
Esempio n. 20
0
 def __init__(self):
     super().__init__()
     self.projectModel = QSqlQueryModel()
     self.settings = QSettings('CAIO', 'Preferences')
     self.totalLocks = self.settings.value('totalLocks')
     self.noOfLocksAdmin = self.settings.value('noOfLocksAdmin')
     self.noOfSomeoneElseLocks = self.settings.value('noOfSomeoneElseLocks')
     self.noOfNobodyLocks = self.settings.value('noOfNobodyLocks')
     self.initialRun = True
     self.initialRunCircular = True
     self.counter = 0
     self.db = QSqlDatabase.addDatabase("QSQLITE")
     dbLocation = str(Path.home()) + '/CAIO/caio.db'
     self.db.setDatabaseName(dbLocation)
     self.setLogs()
     # AUTO REFRESH
     timer = QTimer(self)
     timer.start(1000)
     timer.timeout.connect(lambda: self.setWidget())
     timer.timeout.connect(lambda: self.setLogs())
Esempio n. 21
0
 def check_config(self):
     ip_config = config['DEFAULT'].get('station ip')
     station_id = config['DEFAULT'].get('station id')
     secret = config['DEFAULT'].get('secret key')
     self.ip.setText(ip_config)
     self.station.setText(station_id)
     self.token.setText(secret)
     # todo Ellenőrizni, hogy van-e, és mi van a db-ben
     model2 = QSqlQueryModel()
     query = QSqlQuery(
         f"SELECT * FROM reged_station where secret_key = '{secret}'",
         db=db)
     model2.setQuery(query)
     if model2.record(0).value(0):
         if self.station.text() != model2.record(0).value(
                 1) or self.ip.text() != model2.record(0).value(
                     2) or self.token.text() != model2.record(0).value(3):
             self.valtozott = True
             self.rec_id = model2.record(0).value(0)
     else:
         self.uj_station = True
Esempio n. 22
0
 def torna_valasztas(self, i):
     print(self.tournaments.itemData(i))
     # matches = QSqlRelationalTableModel()
     # matches.setTable("torna_match")
     # matches.setFilter(f'a.torna_id=8889 and a.player1_id=c.player_id and a.player2_id=d.player_id and c.torna_id=a.torna_id and d.torna_id=a.torna_id and a.torna_id=b.torna_id')
     # matches.setFilter(f'torna_name = "{self.tournaments.currentText()}" and torna_resztvevok.torna_id=torna_settings.torna_id and station_id = "{self.station_id}"')
     # matches.setRelation(0, QSqlRelation("torna_settings", "torna_id", "torna_name"))
     # matches.setRelation(2, QSqlRelation("torna_resztvevok", "player_id", "player_name"))
     # matches.setRelation(3, QSqlRelation("torna_resztvevok", "player_id", "player_name"))
     # matches.setRelation(7, QSqlRelation("reged_station", "id", "station_id"))
     # matches.select()
     # print(matches)
     # self.merkozesek.clear()
     # for i in  range(matches.rowCount()):
     #     self.merkozesek.addItem(matches.record(i).value(0) + "\t" +
     #                             str(matches.record(i).value(1)) + "\t" +
     #                             matches.record(i).value(2) + "\t" +
     #                             matches.record(i).value(3) + "\t" +
     #                             matches.record(i).value(4) + "\t" +
     #                             str(matches.record(i).value(5))+ "\t" +
     #                             str(matches.record(i).value(6)))
     matches = QSqlQueryModel()
     # todo itt még nincs táblához kötve a lekérés
     matches_query = QSqlQuery(
         f'SELECT a.match_id,  b.torna_name, c.player_name as nev1, \
     d.player_name as nev2, a.variant, a.sets, a.legsperset FROM `torna_match` a, torna_settings b, torna_resztvevok c, \
     torna_resztvevok d WHERE a.torna_id={self.tournaments.itemData(i)} and a.player1_id=c.player_id and a.player2_id=d.player_id \
     and c.torna_id=a.torna_id and d.torna_id=a.torna_id and a.torna_id=b.torna_id and a.match_status<2'
     )
     matches.setQuery(matches_query)
     self.merkozesek.clear()
     for i in range(matches.rowCount()):
         self.merkozesek.addItem(
             str(matches.record(i).value(0)) + "\t" +
             matches.record(i).value(1) + "\t" +
             matches.record(i).value(2) + "\t" +
             matches.record(i).value(3) + "\t" +
             matches.record(i).value(4) + "\t" +
             str(matches.record(i).value(5)) + "\t" +
             str(matches.record(i).value(6)))
Esempio n. 23
0
    def __init__(self):
        super().__init__()

        self.user_entry = QLineEdit("user5301")
        # self.user_entry.setStyleSheet("font: corbel; font-size: 12px;")
        self.pass_entry = QLineEdit("e", self)
        self.odbc = ""
        self.bars = ""
        self.table_query = ""
        self.pass_entry.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.ru_entry = QLineEdit("328845", self)
        # self.ru_entry.setStyleSheet("font: corbel; font-size: 12px;")
        self.cur_entry = QLineEdit("840")
        # self.cur_entry.setStyleSheet("font: corbel; font-size: 12px;")
        self.balance_entry = QLineEdit("213000001")
        # self.balance_entry.setStyleSheet("font: corbel; font-size: 12px;")
        self.ok_button = QPushButton("Запустить")
        self.ok_button.setStyleSheet(
            "font: corbel; font-size: 12px; color: rgb(0, 0, 255)")
        # self.ok_button.setStyleSheet("color: rgb(160, 70, 70)")
        self.error_label = QLabel("Ошибки будут тут")
        self.error_label.setStyleSheet("color: rgb(255, 0, 0)")

        self.start_button1 = QPushButton("Старт")
        self.stop_button1 = QPushButton("Стоп")
        self.start_button1.setEnabled(True)
        self.stop_button1.setEnabled(False)
        self.start_button1.setStyleSheet("background-color: rgb(81,142,144)")
        self.interval_l = QLabel("Интервал")
        # self.interval_l.setStyleSheet("font: corbel; font-size: 12px; color: rgb(0, 0, 255)")
        self.interval_e = QLineEdit()
        self.timer_id = 0
        self.table = QTableView()
        # Create model
        self.sqm = QSqlQueryModel(parent=self.table)

        self.init_ui()
Esempio n. 24
0
 def get_jogcimdata(self):
     jogcimek_model = QSqlQueryModel()
     query = QSqlQuery("SELECT jogcim FROM jogcim order by jogcim", db=db)
     jogcimek_model.setQuery(query)
     self.jogcim_completer.setModel(jogcimek_model)
Esempio n. 25
0
 def run(self):
     ##        print(getpass.getuser(), self.user_entry.text())
     e = WorkWithOCI(
         "XE", self.user_entry.text(),
         keyring.get_password(getpass.getuser(), self.user_entry.text()))
     #print("Name of database:", e.name)
     # print("Host :", e.host)
     conn = e.open_db()
     if conn:
         self.error_label.setText("Ошибок уже/пока нет")
         query = QSqlQuery()
         query2 = QSqlQuery()
         # Доступность
         if query.exec_(self.bars):
             #print("Q1 done!")
             query.finish()
             # Create model
             self.sqm = QSqlQueryModel(parent=self.table)
             # Сам запрос
             self.sqm.setQuery(
                 self.table_query.format(self.ru_entry.text().strip(),
                                         self.cur_entry.text().strip(),
                                         self.balance_entry.text().strip()))
             if query2.exec_(
                     self.table_query.format(
                         self.ru_entry.text().strip(),
                         self.cur_entry.text().strip(),
                         int(self.balance_entry.text().strip()))):
                 #print("Q2 done!")
                 self.sqm.setQuery(query2)
             else:
                 self.print_and_label("Ошибка 2-го запроса")
                 print(
                     "2-й запрос (",
                     self.table_query.format(
                         self.ru_entry.text().strip(),
                         self.cur_entry.text().strip(),
                         int(self.balance_entry.text().strip())), ") :",
                     query.lastError().text())
             # Задаем заголовки для столбцов модели
             self.sqm.setHeaderData(0, Qt.Horizontal, "Счет")
             self.sqm.setHeaderData(1, Qt.Horizontal, "РУ")
             self.sqm.setHeaderData(2, Qt.Horizontal, "Валюта")
             self.sqm.setHeaderData(3, Qt.Horizontal, "Остаток")
             # self.print_and_label(sqm.lastError().text())
             # Задаем для таблицы только что созданную модель
             self.table.setModel(self.sqm)
             # Not)Скрываем первый столбец, в котором выводится идентификатор
             # self.table.hideColumn(0)
             self.table.setColumnWidth(0, 150)
             self.table.setColumnWidth(1, 60)
             self.table.setColumnWidth(2, 80)
             self.table.setColumnWidth(3, 150)
             # print("sqm.rowCount()", self.sqm.rowCount())
             if self.sqm.rowCount() > 0:
                 frequency = 2500
                 duration = 2000
                 winsound.Beep(frequency, duration)
             conn.close()
             #conn.removeDatabase('qt_sql_default_connection')
         else:
             self.print_and_label("Ошибка первого запроса (", self.bars,
                                  ") :",
                                  query.lastError().text())
     else:
         self.print_and_label("Ошибка открытия базы данных")
Esempio n. 26
0
def new_settings(parent):
    m_id = p1_id = p2_id = set = leg = 0
    var = ""
    # manage_settings_window = GameSettingsDialog()
    # manage_settings_window.show()
    if manage_settings_window.exec_():
        player1 = manage_settings_window.input_player1_name.text()
        player2 = manage_settings_window.input_player2_name.text()
        # A MATCH_ID-T AZ AUTOINCREMENTBŐL KELLENE VISSZAKÉRNI ÉS NEM IMPLICIT RANDOMBÓL GENERÁLNI
        m_id = random.randint(10, 1000000)
        # print(m_id)
        set = manage_settings_window.spin_legs.value()
        leg = manage_settings_window.spin_sets.value()
        if manage_settings_window.gomb_301.isChecked():
            var = "301"
        elif manage_settings_window.gomb_401.isChecked():
            var = "401"
        elif manage_settings_window.gomb_501.isChecked():
            var = "501"
        else:
            var = "701"
        # print(var)
        player1_id_model = QSqlQueryModel()
        query1 = QSqlQuery(
            f"SELECT player_id FROM players where player_name = '{player1}'",
            db=db)
        player1_id_model.setQuery(query1)
        if player1_id_model.record(0).value(0):
            p1_id = int(player1_id_model.record(0).value(0))
        else:
            player_model1 = QSqlTableModel()
            player_model1.setTable("players")
            rec_play1 = player_model1.record()
            rec_play1.remove(0)
            rec_play1.setValue(0, player1)
            if player_model1.insertRecord(-1, rec_play1):
                player_model1.submitAll()
            else:
                db.rollback()
            query1 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player1}'",
                db=db)
            player1_id_model.setQuery(query1)
            p1_id = int(player1_id_model.record(0).value(0))

        player2_id_model = QSqlQueryModel()
        query2 = QSqlQuery(
            f"SELECT player_id FROM players where player_name = '{player2}'",
            db=db)
        player2_id_model.setQuery(query2)
        if player2_id_model.record(0).value(0):
            p2_id = int(player2_id_model.record(0).value(0))
        else:
            player_model2 = QSqlTableModel()
            player_model2.setTable("players")
            rec_play2 = player_model2.record()
            rec_play2.remove(0)
            rec_play2.setValue(0, player2)
            if player_model2.insertRecord(-1, rec_play2):
                player_model2.submitAll()
            else:
                db.rollback()
            query2 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player2}'",
                db=db)
            player2_id_model.setQuery(query2)
            p2_id = int(player2_id_model.record(0).value(0))

        # Match paremeterek rögzítése
        match_model = QSqlTableModel()
        match_model.setTable("match_settings")
        record = match_model.record()
        record.setValue(0, m_id)
        record.setValue(1, p1_id)
        record.setValue(2, p2_id)
        record.setValue(3, var)
        record.setValue(4, set)
        record.setValue(5, leg)
        if match_model.insertRecord(-1, record):
            match_model.submitAll()
        else:
            db.rollback()
        # parent.main_layout.addLayout(parent.match_layout)
        # parent.match_layout.addWidget(parent.cimke)
        # parent.main_layout.addWidget(parent.GameWindow)
        parent.gomb1.setText("OK")
    else:
        # parent.gomb1.setText("Cancel")
        parent.close()
Esempio n. 27
0
                lst.append(
                    query.value('goodname') + ": " +
                    str(query.value('goodcount')) + ' шт.')
                print("Number of record", query.at(), "about record",
                      query.record())
                query.next()
            for p in lst:
                print(p)
    else:
        print("Error in select")

    query.finish()
    window = QtWidgets.QTableView()
    window.setWindowTitle("QSqlQueryModel")
    # Create model
    sqm = QSqlQueryModel(parent=window)
    sqm.setQuery(good_select)
    # Задаем заголовки для столбцов модели
    sqm.setHeaderData(1, QtCore.Qt.Horizontal, "Название")
    sqm.setHeaderData(2, QtCore.Qt.Horizontal, "Количество")
    # Задаем для талицы только что созданную модель
    window.setModel(sqm)
    # Скрываем первый столбец, в котором выводится идентификатор
    window.hideColumn(0)
    window.setColumnWidth(1, 150)
    window.setColumnWidth(2, 60)
    window.resize(230, 130)
    window.show()
    connn.close()
    print("Close. Thanks.")
    sys.exit(app.exec_())
Esempio n. 28
0
def get_addresses_model(parent: QObject = None) -> QSqlQueryModel:
    model = QSqlQueryModel(parent)
    model.setQuery("SELECT distinct address FROM public.customers;")
    if model.lastError().isValid():
        raise RuntimeError(model.lastError().text())
    return model
Esempio n. 29
0
def get_discount_groups_model(parent: QObject = None) -> QSqlQueryModel:
    model = QSqlQueryModel(parent)
    model.setQuery("SELECT distinct discount_group FROM public.merchandise;")
    if model.lastError().isValid():
        raise RuntimeError(model.lastError().text())
    return model
Esempio n. 30
0
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
## $QT_END_LICENSE$
##
#############################################################################

import sys

from PySide2.QtCore import Qt
from PySide2.QtSql import QSqlQueryModel
from PySide2.QtWidgets import QTableView, QApplication

import createdb
from bookdelegate import BookDelegate

if __name__ == "__main__":
    app = QApplication()
    createdb.init_db()

    model = QSqlQueryModel()
    model.setQuery("select title, author, genre, year, rating from books")

    table = QTableView()
    table.setModel(model)
    table.setItemDelegate(BookDelegate())
    table.resize(800, 600)
    table.show()

    sys.exit(app.exec_())