示例#1
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)
示例#2
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()
示例#3
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()
示例#4
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)
示例#5
0
class AllLogsPage(QObject):
    def __init__(self):
        super().__init__()
        self.allLogsModel = ""
        self.settings = QSettings('CAIO', 'Preferences')
        self.initialRun = True
        # self.dbAllLog = QSqlDatabase.addDatabase("QSQLITE")
        # self.dbAllLog.setDatabaseName("caio.db")
        # self.dbAllLog.open()

        # AUTO REFRESH
        timer = QTimer(self)
        timer.start(1000)
        timer.timeout.connect(lambda: self.setLogs())

    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
示例#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)
示例#7
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
 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)
 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)
示例#10
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)
示例#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)
示例#12
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)))
示例#13
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()
示例#14
0
class DashboardPage(QObject):
    setMaxValue = Signal(int)
    setAdminLocks = Signal(int)
    setSomeoneElseLocks = Signal(int)
    setNobodyLocks = Signal(int)

    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())

    def setWidget(self):
        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.setMaxValue.emit(self.totalLocks)
        self.setAdminLocks.emit(self.noOfLocksAdmin)
        self.setSomeoneElseLocks.emit(self.noOfSomeoneElseLocks)
        self.setNobodyLocks.emit(self.noOfNobodyLocks)

    def setLogs(self):
        isLogChanged = self.settings.value('logChanged')
        if isLogChanged == 1 or self.initialRun:
            self.db.open()
            self.projectModel.setQuery(
                "select ID, Date, Time, LockedBy from allLogs order by id desc",
                self.db)
            self.db.close()
            QSqlDatabase.removeDatabase("QSQLITE")
            self.settings.setValue('logChanged', 0)
            self.initialRun = False
class MainWindow(QMainWindow):
    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)
示例#16
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)))
示例#17
0
class MainWindow(QMainWindow):
    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)
示例#18
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
示例#19
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
示例#20
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)))
示例#21
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
示例#22
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()
示例#23
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)
示例#24
0
class Main(QWidget):
    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()

    def on_start(self):
        password = self.pass_entry.text()
        if password == "e":
            self.print_and_label("Вы не ввели пароль!")
        else:
            self.timer_id = self.startTimer(int(self.interval_e.text()))
            self.start_button1.setEnabled(False)
            self.stop_button1.setEnabled(True)

    def on_stop(self):
        print("Таймер остановлен.", self.timer_id)
        if self.timer_id:
            self.killTimer(self.timer_id)
            self.timer_id = 0
            self.start_button1.setEnabled(True)
            self.stop_button1.setEnabled(False)

    def print_and_label(self, text):
        print(text)
        self.error_label.setText(text)

    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("Ошибка открытия базы данных")

    def timerEvent(self, event):
        # self.error_label.setText("Сработал таймер" + str(event.timerId()))

        print("Сработал таймер", str(event.timerId()))
        self.run()

    def init_ui(self):
        file_name = 'ini_balance'
        with open(file_name) as f:
            lines = f.readlines()
            try:
                self.interval_e.setText(lines[0])
            except:
                self.error_label.setText(
                    ' Возможно в первой строке файла ini_balance нет времени таймера!'
                )
            try:
                self.bars = lines[1]
            except:
                self.error_label.setText(
                    ' Возможно во второй строке файла ini_balance нет запроса!'
                )
            try:
                self.table_query = lines[2]
            except:
                self.error_label.setText(
                    ' Возможно в третьей строке файла ini_balance нет запроса!'
                )

        label = QLabel(self)
        label.setAlignment(Qt.AlignRight)
        label.resize(30, 30)
        image = QPixmap("b.jfif", format="JPG").scaled(label.width(),
                                                       label.height())
        #image = QPixmap("mon.png", format="PNG")

        label.setPixmap(image)
        self.group = QGroupBox("Таймер остатка")
        self.group.setStyleSheet("font: corbel; font-size: 14px;")
        v_group = QVBoxLayout()  # Контейнер для группы
        v_group.addWidget(self.start_button1)
        v_group.addWidget(self.stop_button1)
        v_group.addWidget(self.interval_l)
        v_group.addWidget(self.interval_e)
        self.group.setLayout(v_group)

        form = QFormLayout()
        form.addRow("", label)
        form.addRow("По&льзователь", self.user_entry)
        form.addRow("&Пароль", self.pass_entry)
        form.addRow("&МФО области", self.ru_entry)
        form.addRow("&Валюта", self.cur_entry)
        form.addRow("&Необходимый остаток", self.balance_entry)
        form.addRow("", self.ok_button)
        form.addRow("", self.group)
        form.addRow("&Результат", self.table)
        form.addRow("&Ошибки", self.error_label)

        self.setLayout(form)
        # k10 - work with password
        # is_right in - hash, return - T/F; set_p in - pass return - hash
        hash_pass = hashlib.md5(self.pass_entry.text().encode('utf-8'))
        # print("hash", hash_pass)
        # keyring.set_password(getpass.getuser(), self.user_entry.text(), self.pass_entry.text())
        self.pass_entry.editingFinished.connect(
            lambda: k10.keyring_pass(getpass.getuser(), self.user_entry.text(
            ), self.pass_entry, hash_pass, self.ru_entry))
        self.ok_button.clicked.connect(lambda: self.run())
        self.start_button1.clicked.connect(self.on_start)
        self.stop_button1.clicked.connect(self.on_stop)
        self.setGeometry(300, 100, 650, 550)
        self.setWindowTitle('Ждем деньги')

        self.show()
示例#25
0
    def accept(self):
        params = []
        m_id = p1_id = p2_id = set = leg = hc1 = hc2 = 0
        var = ""
        player1 = self.input_player1_name.text()
        player2 = self.input_player2_name.text()
        # todo A MATCH_ID-T VALAMI EGYEDI MÓDON KELL GENERÁLNI(pl. az időbélyeg bizonyos részével)
        m_id = random.randint(10, 1000000)
        leg = self.spin_legs.value()
        set = self.spin_sets.value()
        hc1 = self.handi1.value()
        hc2 = self.handi2.value()
        if self.gomb_301.isChecked():
            var = "301"
        elif self.gomb_401.isChecked():
            var = "401"
        elif self.gomb_501.isChecked():
            var = "501"
        else:
            var = "701"

        if self.best_of.isChecked():
            bestof = 1
        else:
            bestof = 0

        if len(player1) == 0:
            p1_id = 1
            player1 = "Player 1"
        else:
            player1_id_model = QSqlQueryModel()
            query1 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player1}' and type='local' and aktiv=1",
                db=db)
            player1_id_model.setQuery(query1)
            # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
            if player1_id_model.record(0).value(0):
                p1_id = int(player1_id_model.record(0).value(0))
            else:
                # todo beszúrás előtt ellenőritni, hogy egyedi-e. Létezhet versenyen felvitt ugyanolyan név
                player_model1 = QSqlTableModel()
                player_model1.setTable("players")
                rec_play1 = player_model1.record()
                rec_play1.remove(0)
                rec_play1.setValue(0, player1)
                rec_play1.setValue(1, 'local')
                rec_play1.setValue(2, 1)
                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}' and type='local' and aktiv=1",
                    db=db)
                player1_id_model.setQuery(query1)
                # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
                p1_id = int(player1_id_model.record(0).value(0))

        if len(player2) == 0:
            p2_id = 2
            player2 = "Player 2"
        else:
            player2_id_model = QSqlQueryModel()
            query2 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player2}' and type='local' and aktiv=1",
                db=db)
            player2_id_model.setQuery(query2)
            # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
            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)
                rec_play2.setValue(1, 'local')
                rec_play2.setValue(2, 1)
                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}' and type='local' and aktiv=1",
                    db=db)
                player2_id_model.setQuery(query2)
                # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
                p2_id = int(player2_id_model.record(0).value(0))

        # Match paremeterek rögzítése
        now = QDateTime.currentDateTime()
        match_model = QSqlTableModel()
        match_model.setTable("match_settings")
        # todo Best Of... nincs db-ben tárolva
        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, leg)
        record.setValue(5, set)
        record.setValue(6, hc1)
        record.setValue(7, hc2)
        record.setValue(8, now)
        if match_model.insertRecord(-1, record):
            match_model.submitAll()
        else:
            db.rollback()
        params.append(player1)
        params.append(player2)
        params.append(m_id)
        params.append(p1_id)
        params.append(p2_id)
        params.append(var)
        params.append(leg)
        params.append(set)
        params.append(hc1)
        params.append(hc2)
        params.append(bestof)
        self.parent.new_game_window.params = params
        self.parent.new_game_window.refresh()
        super().accept()
示例#26
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
示例#27
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_())
class MainWindow(QMainWindow):
    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)

    def update_query(self, s=None):

        # Get the text values from the widgets.
        track_name = self.track.text()
        track_composer = self.composer.text()
        album_title = self.album.text()

        self.query.bindValue(":track_name", track_name)
        self.query.bindValue(":track_composer", track_composer)
        self.query.bindValue(":album_title", album_title)

        self.query.exec_()
        self.model.setQuery(self.query)
示例#29
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_())
示例#30
0
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (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.QtSql import QSqlQueryModel
from PySide2.QtWidgets import QTableView, QApplication

import createdb

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

    model = QSqlQueryModel()
    model.setQuery("select * from books")

    table_view = QTableView()
    table_view.setModel(model)
    table_view.resize(800, 600)
    table_view.show()
    sys.exit(app.exec_())