示例#1
0
 def makeLCD(self,s):
     lcd = QLCDNumber()
     lcd.setSegmentStyle(2)
     lcd.setFrameStyle(QFrame.Plain)
     lcd.setSmallDecimalPoint(False)
     lcd.setStyleSheet("QLCDNumber { color: %s; background-color: %s;}"%(self.aw.lcdpaletteF[s],self.aw.lcdpaletteB[s]))
     return lcd
示例#2
0
class QSensor(QObject):
    def __init__(self, name: str, units: str) -> None:
        QObject.__init__(self)

        self.name = name
        self.value = 0
        self.units = units

        self.labelName = QLabel()
        self.labelName.setText(self.name + ":")
        self.labelName.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.lcd = QLCDNumber()
        self.lcd.display(self.value)
        self.lcd.setSegmentStyle(QLCDNumber.SegmentStyle.Flat)

        self.labelUnits = QLabel()
        self.labelUnits.setText(self.units)
        self.labelUnits.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

    def __repr__(self) -> str:
        return f"{self.name}: {self.value} {self.units}"

    def __str__(self) -> str:
        return self.__repr__()

    @pyqtSlot(float)
    def update(self, value):
        self.value = value
        self.lcd.display(self.value)
示例#3
0
class Timer(QWidget):
  def __init__(self):
    super().__init__()
    self.initUI()
  
  def initUI(self):
    timer = QTimer(self)
    timer.timeout.connect(self.updtTime)
    self.timeDisplay = QLCDNumber(self)
    self.timeDisplay.setSegmentStyle(QLCDNumber.Filled)
    self.timeDisplay.setDigitCount(8)
    self.updtTime()
    timer.start(1000)

    layout = QHBoxLayout()
    layout.addWidget(self.timeDisplay)

    self.setLayout(layout)

    self.setGeometry(300, 300, 500, 200)
    self.setWindowTitle('Timer')
    self.show()

  def updtTime(self):
    currentTime = QDateTime.currentDateTime().toString('hh:mm:ss')
    self.timeDisplay.display(currentTime)
示例#4
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.lcd = QLCDNumber(self)  # 设置数字类
        self.lcd.setDigitCount(25)
        self.lcd.setMode(QLCDNumber.Dec)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.setStyleSheet(
            "border: 1px solid green; color: green; background: silver;"
        )  # 设置显示的颜色样式
        # vbox = QVBoxLayout()  # 设置布局
        # vbox.addWidget(self.lcd)
        # self.setLayout(vbox)
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('hello')
        dir_path = os.path.abspath(os.path.dirname(__file__)) + '\image\\1.ico'
        self.setWindowIcon(QIcon(dir_path))
        self.show()
        self.timer = QTimer()
        self.timer.start(1)
        self.timer.timeout.connect(self.flush)  # 使用了计时器
        '''
        创建计时器->设置1ms刷新间隔->每次刷新执行flush函数
        '''

    def flush(self):
        # 获取系统当前时间
        dateTime = QDateTime.currentDateTime()
        # 显示的内容
        self.lcd.display(dateTime.toString("yyyy-MM-dd HH:mm:ss.zzz"))
示例#5
0
 def __build_lcd_number_widget(self):
     """Build a LCD Number widget."""
     lcdnumber = QLCDNumber(self)
     lcdnumber.setSegmentStyle(QLCDNumber.Filled)
     lcdnumber.setFixedHeight(40)
     lcdnumber.setFrameStyle(QFrame.NoFrame)
     return lcdnumber
示例#6
0
 def _create_indicator(self, name):
     hbox = QHBoxLayout()
     label = QLabel(name)
     display = QLCDNumber(7)
     display.setSegmentStyle(QLCDNumber.Flat)
     hbox.addWidget(display)
     hbox.addWidget(label)
     return hbox, display
示例#7
0
class MY_TIME(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.init_timer()

    def update_time(self):
        # 设置时间元祖  time.localtime()  获取本地时间
        self.lcd.display(time.strftime('%X', time.localtime()))

    def init_timer(self):
        self.timer = QTimer()
        #设置定时器,每一秒触发一次 timeout  信号
        self.timer.setInterval(1000)
        #启动定时器
        self.timer.start()
        self.timer.timeout.connect(self.update_time)

    def initUI(self):
        self.resize(250, 100)
        self.setWindowTitle('王守鹏')
        self.move_center()
        self.lcd = QLCDNumber()
        #设置要显示的数字个数
        self.lcd.setDigitCount(10)
        #采用的是十进制模式
        self.lcd.setMode(QLCDNumber.Dec)
        #设置平面模式
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        #设置时间元祖  time.localtime()  获取本地时间
        self.lcd.display(time.strftime('%X', time.localtime()))
        #构建一个盒子布局
        self.main_layout = QVBoxLayout()
        #把上面的组件添加进盒子布局
        self.main_layout.addWidget(self.lcd)
        #设置组件居中
        self.main_layout.setAlignment(Qt.AlignCenter)
        #设置给顶层布局
        self.setLayout(self.main_layout)
        #设置界面颜色
        self.main_bg = QPalette()
        #设置颜色为蓝色
        self.main_bg.setColor(QPalette.Background, Qt.darkGreen)
        #设置自动填充背景颜色
        self.setAutoFillBackground(True)
        #把颜色设置给顶级窗口
        self.setPalette(self.main_bg)

    def move_center(self):
        #设置矩形
        m_rect = self.frameGeometry()
        #获取这个屏幕的中心点
        w_center_point = QDesktopWidget().availableGeometry().center()
        m_rect.moveCenter(w_center_point)
        #从左上角开始移动,直到中间
        self.move(m_rect.topLeft())
        self.show()
示例#8
0
class MyTime(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.init_timer()
    #规定槽函数 更新时间
    def update_time(self):
        #获取本地时间 显示到窗口
        self.lcd.display(time.strftime('%X',time.localtime()))
    #实现定时器  信号 和槽函数
    def init_timer(self):
        #初始化定时器
        self.timer = QTimer()
        #设置触发信号,1000毫秒
        self.timer.setInterval(1000)
        #启动定时器
        self.timer.start()
        #信号触发
        self.timer.timeout.connect(self.update_time)
    #实现界面所有编写  实例方法 this
    def initUI(self):
        #设置组件大小 宽高251px * 150px
        self.resize(251,150)
        #设置窗口标题
        self.setWindowTitle('构建创意时钟')
        #设置窗口LOGO
        self.setWindowIcon(QIcon('C:/Users/19845/Desktop/a.jpg'))
        #初始化 调色板
        self.plt = QPalette()
        #设置背景颜色 深青色
        self.plt.setColor(QPalette.Background,Qt.darkCyan)
        #设置当前窗体自动填充渲染背景颜色
        self.setAutoFillBackground(True)
        #设置顶层布局
        self.setPalette(self.plt)
        #初始化 LCD数字组件
        self.lcd = QLCDNumber()
        #设置显示数字个数
        self.lcd.setDigitCount(10)
        #设置显示样式的模式,为平面模式
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        #设置显示模式,为10进制
        self.lcd.setMode(QLCDNumber.Dec)
        #获取本地时间,显示到窗口中
        self.lcd.display(time.strftime('%X',time.localtime()))
        #初始化盒子布局
        self.box = QVBoxLayout()
        #把要显示的LCD界面添加到布局中 统一管理
        self.box.addWidget(self.lcd)
        #设置组件到窗口中间位置显示
        self.box.setAlignment(Qt.AlignCenter)
        #将所有逻辑设置到顶层布局中
        self.setLayout(self.box)
        #显示所有ui界面
        self.show()
示例#9
0
class MyTime(QWidget):
    # 构造方法
    def __init__(self):     # self代表当前实例对象的本身 ps:不是类本身
        super().__init__()
        self.initUI()
        self.init_timer()
    def update_time(self):
        # 获取当前的系统时间
        self.lcd.display(time.strftime('%X',time.localtime()))
    def init_timer(self):
        # 定时器
        self.timer = QTimer()
        # 间隔0.5s发送一次信号
        self.timer.setInterval(500)
        # 启动定时器
        self.timer.start()
                # 信号 和 槽函数
        self.timer.timeout.connect(self.update_time)
    def initUI(self):
        # 窗口组件的大小   251px * 150
        self.resize(251,150)
        # 窗口组件的名称
        self.setWindowTitle('不完美时钟')
        # 设置窗口图标
        self.setWindowIcon(QIcon('微信图片_20180706210835.jpg'))
        # 颜色调色板
        self.pa = QPalette()
        # 设置背景颜色为深黄色
        self.pa.setColor(QPalette.Background,Qt.darkCyan)
        self.setAutoFillBackground(True)
        self.setPalette(self.pa)

        self.lcd = QLCDNumber()
        # 设置数字的个数为10个
        self.lcd.setDigitCount(10)
        # 设置显示的数字模式为10进制
        self.lcd.setMode(QLCDNumber.Dec)
        # 设置展示的模式为水平
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        # 获取当前的系统时间
        self.lcd.display(time.strftime('%X',time.localtime()))
        # 初始化一个盒子布局
        self.main_layout = QVBoxLayout()
        # 把时间添加到布局中
        self.main_layout.addWidget(self.lcd)
        # 设置组件到布局的中间
        self.main_layout.setAlignment(Qt.AlignCenter)
        # 将子布局 设置到 顶层布局
        self.setLayout(self.main_layout)


        # 显示布局
        self.show()
示例#10
0
class CountDownWidget(QWidget):
    def __init__(self, parent=None):
        # コンストラクタ
        QWidget.__init__(self, parent=parent)
        self.interval = 10

        self.setup_ui()

    def setup_ui(self):
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QtCore.Qt.white)
        self.setPalette(p)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.timer = QtCore.QTimer(parent=self)
        self.timer.setInterval(self.interval)
        self.timer.timeout.connect(self.do_countdown)

        self.lcd_number = QLCDNumber(parent=self)
        self.lcd_number.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)
        self.lcd_number.setFrameStyle(QFrame.NoFrame)
        self.lcd_number.setSegmentStyle(QLCDNumber.Flat)
        self.lcd_number.setDigitCount(6)

        layout = QVBoxLayout()
        layout.addWidget(self.lcd_number)
        self.setLayout(layout)

        self.reset_count()

    def update_display(self):
        self.lcd_number.display("%6.2f" % (self.count / 100))
        self.lcd_number.update()

    def do_countdown(self):
        self.count -= 1
        self.update_display()
        if self.count <= 0:
            self.stop_countdown()

    def start_countdown(self):
        if self.count > 0:
            self.timer.start()

    def stop_countdown(self):
        self.timer.stop()

    def reset_count(self):
        self.count = 18000
        self.update_display()
示例#11
0
class DiodeInterface(QWidget):
    def __init__(self, label, parentSerial=None, unit='V'):

        super().__init__()

        self.a = 1
        self.b = 0
        self.label = label
        self.unit = unit

        self.serial = parentSerial

        self.initUI(label, unit)

    def init_widgets(self, label, unit):

        self.labelWidget = QLabel(label)
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(2)
        self.unitWidget = QLabel(unit)

    def init_layout(self):

        layout = QHBoxLayout()

        layout.addWidget(self.labelWidget)
        layout.addWidget(self.lcd, 1)
        layout.addWidget(self.unitWidget)

        self.setLayout(layout)

    def initUI(self, label, unit):

        self.init_widgets(label, unit)
        self.init_layout()

    def measure(self, id):

        val = self.serial.query('M{:0}'.format(id))
        self.lcd.display(self.a * val + self.b)

    def set_settings(self, a, b, label, unit):

        self.a = a
        self.b = b
        self.label = label
        self.unit = unit

        self.labelWidget.setText(label)
        self.unitWidget.setText(unit)
示例#12
0
class Soc(QWidget):
    def __init__(self, parent):

        super(Soc, self).__init__(parent)

        self.arguments = Arg_Class()

        self.socValue = 0.0

        self.socLCD = QLCDNumber(self)
        self.socLCD.display(
            str(int(self.socValue)).zfill(4) + '.' +
            str((self.socValue - int(self.socValue)) * 10).zfill(4))
        self.socLCD.setFrameShape(QFrame.NoFrame)
        self.socLCD.setSegmentStyle(QLCDNumber.Flat)
        #self.socLCD.move(30,100)
        self.socLCD.move(0, 20)
        self.socLCD.resize(70, 80)

        self.socLabel = QLabel(self)
        self.socLabel.setText("soc: ")
        self.socLabel.move(10, 10)
        self.socLCD.show()
        self.socLabel.show()

    @pyqtSlot(float)
    def soc_update(self, value):
        if value < 0:
            value = 0
        self.socLCD.display(value)
        self.socValue = value
        self.update()
        #self.socGauge.display(str(int(self.socValue)).zfill(2)+'.'+ str((self.socValue - int(self.socValue))*10).zfill(2))

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setPen(Qt.white)

        qp.drawRect(70, 20, 70, 180)
        qp.drawRect(96, 10, 20, 10)
        if self.socValue < 0:
            self.socValue = 0
        if self.socValue < 20:
            qp.setBrush(Qt.red)
        else:
            qp.setBrush(Qt.green)

        qp.drawRect(70, 20 + (180 * (1 - (self.socValue / 100))), 70,
                    ((180 * self.socValue / 100)))
示例#13
0
class CountDownWidget(QWidget):
    '''
    classdocs
    '''
    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent=parent)
        self.interval = 10
        self.setup_ui()
    '''
    実際の初期化関数
    '''
    def setup_ui(self):
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.timer = QTimer(parent=self)
        self.timer.setInterval(self.interval)
        self.timer.timeout.connect(self.do_countdown)
        self.lcd_number = QLCDNumber(parent=self)
        self.lcd_number.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.lcd_number.setFrameStyle(QFrame.NoFrame)
        self.lcd_number.setSegmentStyle(QLCDNumber.Flat)
        self.lcd_number.setDigitCount(6)

        layout = QVBoxLayout()
        layout.addWidget(self.lcd_number)
        self.setLayout(layout)

        self.reset_count()

    def update_display(self):
        self.lcd_number.display("%6.2f" % (self.count / 100))
        self.lcd_number.update()
    def do_countdown(self):
        self.count -= 1
        self.update_display()
        if self.count <= 0:
            self.stopcountdown()
    def start_countdown(self):
        if self.count > 0:
            self.timer.start()
    def stop_countdown(self):
        self.timer.stop()
    def reset_count(self):
        self.count = 18000
        self.update_display()
示例#14
0
class MyTimer(QWidget):
    def __init__(self):
        super(MyTimer, self).__init__()
        self.lcd = QLCDNumber()
        self.lcd.setDigitCount(10)
        self.lcd.setMode(QLCDNumber.Dec)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)

        layout = QVBoxLayout()
        layout.addWidget(self.lcd)
        self.setLayout(layout)
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.start()
        self.timer.timeout.connect(self.onTimerOut)

    def onTimerOut(self):
        self.lcd.display(time.strftime("%X", time.localtime()))
示例#15
0
class CountDownTimer(QLCDNumber):
    """
    time_allocation: positive integer, indicating the allocated time for user
    time_value: started as time_allocation, and dynamically changed every second
    """

    def __init__(self, time_allocation=15, parent=None):
        super(CountDownTimer, self).__init__(parent)
        self.time_allocation = time_allocation
        self.time_value = self.time_allocation

        # timer
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.advance_time)

        # LCD time display
        self.lcd = QLCDNumber(self)
        self.lcd.setDigitCount(3)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.display(self.time_value)

    def restart_timer(self):
        self.time_value = self.time_allocation
        self.lcd.display(self.time_value)
        palette = self.lcd.palette()
        palette.setColor(palette.WindowText, QColor(0, 0, 0))
        self.lcd.setPalette(palette)
        self.timer.start(1000)

    def advance_time(self):
        self.time_value -= 1

        # Yellow - five seconds left
        if self.time_value == 5:
            palette = self.lcd.palette()
            palette.setColor(palette.WindowText, QColor(255, 153, 0))
            self.lcd.setPalette(palette)

        # Red - no time left
        if self.time_value == 0:
            palette = self.lcd.palette()
            palette.setColor(palette.WindowText, QColor(255, 0, 0))
            self.lcd.setPalette(palette)
        self.lcd.display(self.time_value)
示例#16
0
    def __init__(self):
        super(MainScreen, self).__init__()

        self.mainGame = game.Game()
        nextTetrominoLabel = QLabel()
        nextTetrominoLabel.setFrameStyle(QFrame.Box | QFrame.Raised)
        nextTetrominoLabel.setAlignment(Qt.AlignCenter)

        levelLcd = QLCDNumber(2)
        levelLcd.setSegmentStyle(QLCDNumber.Filled)
        linesLcd = QLCDNumber(5)
        linesLcd.setSegmentStyle(QLCDNumber.Filled)

        startButton = QPushButton("&Start")
        startButton.setFocusPolicy(Qt.NoFocus)
        botButton = QPushButton("&Activate Bot")
        botButton.setFocusPolicy(Qt.NoFocus)
        pauseButton = QPushButton("&Pause")
        pauseButton.setFocusPolicy(Qt.NoFocus)

        currentGame = self.mainGame
        startButton.clicked.connect(currentGame.start)
        pauseButton.clicked.connect(currentGame.pause)
        botButton.clicked.connect(currentGame.activateBot)
        currentGame.linesClearedChanged.connect(linesLcd.display)
        currentGame.levelChanged.connect(levelLcd.display)
        currentGame.nextTetrominoChanged.connect(nextTetrominoLabel.setPixmap)

        layout = QGridLayout()
        layout.addWidget(self.createLabel("NEXT"), 0, 0)
        layout.addWidget(nextTetrominoLabel, 1, 0)
        layout.addWidget(self.createLabel("LEVEL"), 2, 0)
        layout.addWidget(levelLcd, 3, 0)
        layout.addWidget(startButton, 4, 0)
        layout.addWidget(currentGame, 0, 1, 6, 1)
        layout.addWidget(self.createLabel("LINES CLEARED"), 2, 2)
        layout.addWidget(linesLcd, 3, 2)
        layout.addWidget(botButton, 4, 2)
        layout.addWidget(pauseButton, 5, 2)
        self.setLayout(layout)

        self.setWindowTitle("Tetris")
        self.resize(550, 370)
示例#17
0
class CounterWindow(QWidget):
    myCounter = 0
    lcd = 0
    
    def __init__(self):
        super().__init__()

        label1 = QLabel('Counter value:', self)
        self.lcd = QLCDNumber(self)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.display(self.myCounter)
        
        # Create box layout and add elements to it
        vbox = QVBoxLayout()
        vbox.addWidget(label1)
        vbox.addWidget(self.lcd)
        self.setLayout(vbox)
        
        # Set size of the window
        self.resize(400, 150)
        # Set position on the screen
        self.move(400, 400)
        self.setWindowTitle('New window')
        self.setWindowIcon(QIcon('web.png'))
        print('Counter window initialized')
        
    # Return current state of this window
    def getWindowState(self):
        print('Visibility = ', self.isVisible())
        return self.isVisible()
        
    # Increment counter and update LCD in window
    def add(self):
        self.myCounter = self.myCounter + 1
        self.lcd.display(self.myCounter)
        print(self.myCounter)
        
    # Decrement counter and update LCD in window   
    def subtract(self):
        self.myCounter = self.myCounter - 1
        self.lcd.display(self.myCounter)
        print(self.myCounter)
示例#18
0
class Channel3(QWidget):
    def __init__(self, parent, name, x, y, value):
        super(Channel3, self).__init__(parent)

        self.label = QLabel(name, self)
        self.label.resize(CHANNEL_WIDTH, 20)
        self.label.move(x, y)

        self.gauge = QLCDNumber(self)
        self.gauge.display(value)
        self.gauge.move(x, y + 20)
        self.gauge.resize(CHANNEL_WIDTH, CHANNEL_HEIGHT)
        self.gauge.setFrameShape(QFrame.NoFrame)
        self.gauge.setSegmentStyle(QLCDNumber.Flat)

    @pyqtSlot(float)
    def channel_update(self, value):
        self.gauge.display(value)
        self.value = value
        self.update()
示例#19
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.resize(600, 600)

        self.lcd_1 = QLCDNumber(self)  # 1
        self.lcd_1.setDigitCount(10)
        self.lcd_1.display(1234567890)

        self.lcd_2 = QLCDNumber(self)  # 2
        self.lcd_2.setSegmentStyle(QLCDNumber.Flat)
        # self.lcd_2.setSmallDecimalPoint(True)
        self.lcd_2.setDigitCount(10)
        self.lcd_2.display(0.1456789)

        self.lcd_3 = QLCDNumber(self)  # 3
        self.lcd_3.setSegmentStyle(QLCDNumber.Filled)
        self.lcd_3.display('HELLO')

        self.lcd_4 = QLCDNumber(self)  # 4
        self.lcd_4.setSegmentStyle(QLCDNumber.Outline)
        self.lcd_4.setMode(QLCDNumber.Hex)
        self.lcd_4.setDigitCount(6)
        self.lcd_4.display(666)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.lcd_1)
        self.v_layout.addWidget(self.lcd_2)
        self.v_layout.addWidget(self.lcd_3)
        self.v_layout.addWidget(self.lcd_4)

        self.setLayout(self.v_layout)
示例#20
0
class MainWindow(Ui_MainWindow, QMainWindow):
    """
    主界面二次设计
    """
    def __init__(self):
        super(MainWindow, self).__init__()

        # 获取桌面尺寸
        desktop = QApplication.desktop()
        desk_width = desktop.screenGeometry().width()
        desk_height = desktop.screenGeometry().height()

        # 摄像头图像设置
        self.frame = DIYLabel(self)
        self.frame.setGeometry(0, 0, desk_width, desk_height)

        self.setupUi(self)

        # 按钮定位
        self.buttons = [
            self.att_rec, self.face_login, self.face_rec, self.face_reg
        ]
        map(
            lambda x: x.move(
                desk_width * 0.80, desk_height * 0.33 + self.buttons.index(x) *
                (x.height() + 8)), self.buttons)
        map(lambda x: x.raise_(), self.buttons)

        # 设置时钟
        self.clock = QLCDNumber(self)
        self.clock.setDigitCount(10)
        self.clock.setMode(QLCDNumber.Dec)
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.display(time.strftime("%X", time.localtime()))
        self.clock.setStyleSheet("QLCDNumber{color:rgba(255,0,0,100);}")
        self.clock.resize(280, 120)
        self.clock.move(50, desk_height - 30 - self.clock.height())

        self.setWindowFlags(Qt.FramelessWindowHint)  # 隐藏窗口
        self.showFullScreen()  # 窗体全屏
示例#21
0
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.game = Game(4)  # Make game with 4 players

        self.sig = Signals()
        endTurnButton = QPushButton("&EndTurn", self)
        endTurnButton.clicked.connect(self.endTurn)
        endTurnButton.move(1260, 720)
        turnLcd = QLCDNumber(3, self)
        turnLcd.move(90, 715)
        turnLcd.setSegmentStyle(QLCDNumber.Filled)
        turnLcd.resize(60, 40)
        turnTxt = QLabel("Turn:", self)
        turnFont = QFont()
        turnFont.setPointSize(20)
        turnTxt.setFont(turnFont)
        turnTxt.move(20, 720)

        self.sig.turnChanged.connect(turnLcd.display)
        self.sig.turnChanged.emit(self.game.turn)

        quitB = QPushButton("&Quit", self)
        quitB.clicked.connect(self.quit)
        quitB.move(1150, 720)

        self.showPlayerInfo()

        self.coords = []
        self.setWindowTitle("Territory War")
        n = self.game.map.dim
        self.makeMap(1100 // n, 600 // n, n)
        self.setWindowState(Qt.WindowFullScreen)
        self.setFixedSize(self.size())

        self.showArmies()
        self.addDiplomacyLabels()

        thread = threading.Thread(target=self.game.start, args=(0, ))
        thread.start()
示例#22
0
class ShiZhong(QWidget):
    def __init__(self):
        super(ShiZhong, self).__init__()
        self.initUI()
        self.init_timer()

    def initUI(self):
        self.resize(250, 150)
        self.setWindowTitle('电子时钟By LC')
        self.move_center()
        self.m = QPalette()
        self.m.setColor(QPalette.Background, Qt.green)
        self.setAutoFillBackground(True)
        self.setPalette(self.m)
        self.lcd = QLCDNumber()
        self.lcd.setDigitCount(10)
        self.lcd.setMode(QLCDNumber.Dec)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.display(time.strftime("%X", time.localtime()))
        self.m_layout = QVBoxLayout()
        self.m_layout.addWidget(self.lcd)
        self.m_layout.setAlignment(Qt.AlignCenter)
        self.setLayout(self.m_layout)
        self.show()

    def init_timer(self):
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.start()
        self.timer.timeout.connect(self.update_time)

    def update_time(self):
        self.lcd.display(time.strftime("%X", time.localtime()))

    def move_center(self):
        m_rect = self.frameGeometry()
        w_center_point = QDesktopWidget().availableGeometry().center()
        m_rect.moveCenter(w_center_point)
        self.move(m_rect.topLeft())
示例#23
0
    def __init__(self):
        super(TetrixWindow, self).__init__()

        self.board = TetrixBoard()

        nextPieceLabel = QLabel()
        nextPieceLabel.setFrameStyle(QFrame.Box | QFrame.Raised)
        nextPieceLabel.setAlignment(Qt.AlignCenter)
        self.board.setNextPieceLabel(nextPieceLabel)

        scoreLcd = QLCDNumber(5)
        scoreLcd.setSegmentStyle(QLCDNumber.Filled)
        levelLcd = QLCDNumber(2)
        levelLcd.setSegmentStyle(QLCDNumber.Filled)
        linesLcd = QLCDNumber(5)
        linesLcd.setSegmentStyle(QLCDNumber.Filled)

        startButton = QPushButton("&Start")
        startButton.setFocusPolicy(Qt.NoFocus)
        quitButton = QPushButton("&Quit")
        quitButton.setFocusPolicy(Qt.NoFocus)
        pauseButton = QPushButton("&Pause")
        pauseButton.setFocusPolicy(Qt.NoFocus)

        startButton.clicked.connect(self.board.start)
        pauseButton.clicked.connect(self.board.pause)
        quitButton.clicked.connect(QApplication.instance().quit)
        self.board.scoreChanged.connect(scoreLcd.display)
        self.board.levelChanged.connect(levelLcd.display)
        self.board.linesRemovedChanged.connect(linesLcd.display)

        layout = QGridLayout()
        layout.addWidget(self.createLabel("NEXT"), 0, 0)
        layout.addWidget(nextPieceLabel, 1, 0)
        layout.addWidget(self.createLabel("LEVEL"), 2, 0)
        layout.addWidget(levelLcd, 3, 0)
        layout.addWidget(startButton, 4, 0)
        layout.addWidget(self.board, 0, 1, 6, 1)
        layout.addWidget(self.createLabel("SCORE"), 0, 2)
        layout.addWidget(scoreLcd, 1, 2)
        layout.addWidget(self.createLabel("LINES REMOVED"), 2, 2)
        layout.addWidget(linesLcd, 3, 2)
        layout.addWidget(quitButton, 4, 2)
        layout.addWidget(pauseButton, 5, 2)
        self.setLayout(layout)

        self.setWindowTitle("Tetrix")
        self.resize(550, 370)
示例#24
0
    def __init__(self):
        super(TetrixWindow, self).__init__()

        self.board = TetrixBoard()

        nextPieceLabel = QLabel()
        nextPieceLabel.setFrameStyle(QFrame.Box | QFrame.Raised)
        nextPieceLabel.setAlignment(Qt.AlignCenter)
        self.board.setNextPieceLabel(nextPieceLabel)

        scoreLcd = QLCDNumber(5)
        scoreLcd.setSegmentStyle(QLCDNumber.Filled)
        levelLcd = QLCDNumber(2)
        levelLcd.setSegmentStyle(QLCDNumber.Filled)
        linesLcd = QLCDNumber(5)
        linesLcd.setSegmentStyle(QLCDNumber.Filled)

        startButton = QPushButton("&Start")
        startButton.setFocusPolicy(Qt.NoFocus)
        quitButton = QPushButton("&Quit")
        quitButton.setFocusPolicy(Qt.NoFocus)
        pauseButton = QPushButton("&Pause")
        pauseButton.setFocusPolicy(Qt.NoFocus)

        startButton.clicked.connect(self.board.start)
        pauseButton.clicked.connect(self.board.pause)
        quitButton.clicked.connect(QApplication.instance().quit)
        self.board.scoreChanged.connect(scoreLcd.display)
        self.board.levelChanged.connect(levelLcd.display)
        self.board.linesRemovedChanged.connect(linesLcd.display)

        layout = QGridLayout()
        layout.addWidget(self.createLabel("NEXT"), 0, 0)
        layout.addWidget(nextPieceLabel, 1, 0)
        layout.addWidget(self.createLabel("LEVEL"), 2, 0)
        layout.addWidget(levelLcd, 3, 0)
        layout.addWidget(startButton, 4, 0)
        layout.addWidget(self.board, 0, 1, 6, 1)
        layout.addWidget(self.createLabel("SCORE"), 0, 2)
        layout.addWidget(scoreLcd, 1, 2)
        layout.addWidget(self.createLabel("LINES REMOVED"), 2, 2)
        layout.addWidget(linesLcd, 3, 2)
        layout.addWidget(quitButton, 4, 2)
        layout.addWidget(pauseButton, 5, 2)
        self.setLayout(layout)

        self.setWindowTitle("Tetrix")
        self.resize(550, 370)
示例#25
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.resize(600, 600)

        #  实例化一个QLCDNumber控件,
        #  然后通过setDiditCount()方法来设置一共可以显示多少为数字;
        self.lcd_1 = QLCDNumber(self)
        self.lcd_1.setDigitCount(10)
        self.lcd_1.display(1234567890)

        # lcd_2显示浮点型数字
        self.lcd_2 = QLCDNumber(self)
        # 通过setSegmentStyle()可以设置显示屏数字样式
        """
        常量                  值           描述
        QLCDNumber.Outline  0           让内容浮显,其颜色显示屏背景颜色相同
        QLCDNumber.Filled   1           让内容浮显,颜色窗口标题相同
        QLCDNumber.Flat     2           让内容扁平化显示,颜色同窗口标题颜色相同
        """
        self.lcd_2.setSegmentStyle(QLCDNumber.Flat)

        # setSmallDecimalPoint(bool)方法可以设置小数点的显示方式:
        # 若为True,那么小数点就会在两个数字之间显示出来,而不会单独占一个位置。如果为False,那就会单独占位(默认为False)。
        # self.lcd_2.setSmallDecimalPoint(True)
        self.lcd_2.setDigitCount(10)
        self.lcd_2.display(0.123456789)

        # 3. lcd_3显示的为字符串,可以显示的字母种类有限:A, B, C, D, E, F, h, H, L,
        # o, P, r, u, U, Y, O/0, S/5, g/9;
        self.lcd_3 = QLCDNumber(self)  # 3
        self.lcd_3.setSegmentStyle(QLCDNumber.Filled)
        self.lcd_3.display('HELLO')

        self.lcd_4 = QLCDNumber(self)  # 4
        self.lcd_4.setSegmentStyle(QLCDNumber.Outline)
        self.lcd_4.setMode(QLCDNumber.Hex)
        self.lcd_4.setDigitCount(6)
        self.lcd_4.display(666)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.lcd_1)
        self.v_layout.addWidget(self.lcd_2)
        self.v_layout.addWidget(self.lcd_3)
        self.v_layout.addWidget(self.lcd_4)

        self.setLayout(self.v_layout)
示例#26
0
文件: game.py 项目: trawl/gamelog
class GamePlayerWidget(QGroupBox):

    def __init__(self, nick, colour=None, parent=None):
        super(GamePlayerWidget, self).__init__(parent)
        self.player = nick
        self.pcolour = colour
        self.initUI()

    def initUI(self):
        #        self.setMinimumWidth(300)
        self.mainLayout = QHBoxLayout(self)
#         self.mainLayout.addStretch()
        self.scoreLCD = QLCDNumber(self)
        self.scoreLCD.setSegmentStyle(QLCDNumber.Flat)
        self.mainLayout.addWidget(self.scoreLCD)
        self.scoreLCD.setNumDigits(3)
        self.scoreLCD.setFixedSize(100, 60)
        self.scoreLCD.display(0)
        css = "QLCDNumber {{ color:rgb({},{},{});}}"
        self.scoreLCD.setStyleSheet(css.format(self.pcolour.red(),
                                               self.pcolour.green(),
                                               self.pcolour.blue()))

        self.nameLabel = QLabel(self)
        self.nameLabel.setText(self.player)
        sh = ("QLabel {{ font-size: 32px; font-weight: "
              "bold; color:rgb({},{},{});}}")
        self.nameLabel.setStyleSheet(sh.format(self.pcolour.red(),
                                               self.pcolour.green(),
                                               self.pcolour.blue()))
        self.mainLayout.addWidget(self.nameLabel)

        self.dealerPixmap = QtGui.QPixmap('icons/cards.png')
        self.nonDealerPixmap = QtGui.QPixmap()
        self.winnerPixmap = QtGui.QPixmap('icons/winner.png')

        self.iconlabel = IconLabel(self)
        self.iconlabel.setFixedSize(50, 50)
        self.iconlabel.setScaledContents(True)
        self.mainLayout.insertWidget(0, self.iconlabel)
#         self.mainLayout.addStretch()
        self.unsetDealer()

    def updateDisplay(self, points):
        if points >= 1000:
            self.scoreLCD.setNumDigits(4)
        self.scoreLCD.display(points)

    def setDealer(self): self.iconlabel.setPixmap(self.dealerPixmap)

    def unsetDealer(self): self.iconlabel.setPixmap(self.nonDealerPixmap)

    def setWinner(self): self.iconlabel.setPixmap(self.winnerPixmap)

    def setColour(self, colour):
        self.pcolour = colour
        css = "QLCDNumber {{ color:rgb({},{},{});}}"
        self.scoreLCD.setStyleSheet(css.format(self.pcolour.red(),
                                               self.pcolour.green(),
                                               self.pcolour.blue()))
        sh = ("QLabel {{ font-size: 32px; font-weight: bold; "
              "color:rgb({},{},{});}}")
        self.nameLabel.setStyleSheet(sh.format(self.pcolour.red(),
                                               self.pcolour.green(),
                                               self.pcolour.blue()))
示例#27
0
class Placar(QMainWindow):
    def __init__(self):
        super().__init__()

        self.title = 'Placar para gincanas'
        self.top = 0
        self.left = 0
        self.width = 1366
        self.height = 768

        self.valorPlacarA = 0
        self.valorPlacarB = 0

        self.initWindow()
        self.cronoWindow = Cronometro()

    def initWindow(self):

        #espaço em branco
        espaco = QWidget()
        espaco.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        #Titulo do programa
        self.labelTituloJanela = QLabel(' PLACAR GINCANA', self)
        self.labelTituloJanela.setGeometry(450, 10, 430, 100)
        self.labelTituloJanela.setStyleSheet(
            'QLabel {font: 45px; color: white; font: bold; background-color: #19B5FE; border-radius: 10px}'
        )

        #Seção dos LCDS
        self.lcdPlacar1 = QLCDNumber(self)
        self.lcdPlacar2 = QLCDNumber(self)
        self.lcdPlacar1.setGeometry(50, 120, 300, 250)
        self.lcdPlacar2.setGeometry(940, 120, 300, 250)
        self.lcdPlacar1.setStyleSheet(
            'QLCDNumber {background-color: #000000; color: red; font: bold}')
        self.lcdPlacar1.setSegmentStyle(2)  # QLCDNumber::SegmentStyle
        self.lcdPlacar2.setStyleSheet(
            'QLCDNumber {background-color: #000000; color: red; font: bold}')
        self.lcdPlacar2.setSegmentStyle(2)

        #Label dos nomes dos grupos
        self.labelGrupA = QLabel('Grupo A', self)
        self.labelGrupB = QLabel('Grupo B', self)
        self.labelGrupA.setGeometry(125, 20, 200, 100)
        self.labelGrupA.setStyleSheet('QLabel {font: 40px; font: bold;}')
        self.labelGrupB.setStyleSheet('QLabel {font: 40px; font: bold}')
        self.labelGrupB.setGeometry(1010, 20, 200, 100)

        #Label do cronometro
        self.labelCrono = QLabel(' 00:00 ', self)
        self.labelCrono.setGeometry(130, 490, 170, 100)
        self.labelCrono.setStyleSheet(
            'QLabel {background-color: #336E7B; color: white; font: 50px; border: None; border-radius: 20px}'
        )

        #Label contendo a imagem central do programa
        self.imagemLabel = QLabel(self)
        pixmap = QPixmap('imagens/competir.png')
        self.imagemLabel.setPixmap(pixmap)
        self.imagemLabel.setGeometry(490, 120, 330, 348)

        #Botões de pontuar os grupos
        self.bntGrupA = QPushButton('Pontuar Grupo A', self)
        self.bntGrupB = QPushButton('Pontuar Grupo B', self)
        self.bntGrupA.setGeometry(370, 520, 200, 60)
        self.bntGrupB.setGeometry(690, 520, 200, 60)
        self.bntGrupA.setStyleSheet(
            'QPushButton {font: 23px; font: bold; background-color: #0AEB7E}')
        self.bntGrupB.setStyleSheet(
            'QPushButton {font: 23px; font: bold; background-color: #0AEB7E}')

        #Spin para definir a pontução (Está entre os dois botões)
        self.spinBox = QSpinBox(self)
        self.spinBox.setMaximum(100)
        self.spinBox.setGeometry(592, 520, 90, 60)
        self.spinBox.setStyleSheet('QSpinBox {font: 50px}')

        #Actions Buttons pontuação
        self.bntGrupA.clicked.connect(lambda: self.setValorLcd(1))
        self.bntGrupB.clicked.connect(lambda: self.setValorLcd(2))

        #Seção do cronômetro
        self.labelCronometro = QLabel('Cronometro', self)
        #self.labelCronometro.setIcon(QtGui.QIcon('crono'))
        self.labelCronometro.setStyleSheet(
            'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}'
        )
        self.labelCronometro.setGeometry(145, 440, 150, 50)

        self.bntIniciarCrono = QPushButton('INICIAR', self)
        self.bntIniciarCrono.setGeometry(130, 590, 185, 50)
        self.bntIniciarCrono.setStyleSheet(
            'QPushButton {font: 20px; color: black; font: bold; background-color: #ECF0F1; border-radius: 10px}'
        )
        self.bntIniciarCrono.setIcon(QtGui.QIcon('imagens/play'))
        self.bntIniciarCrono.setCheckable(True)
        self.bntIniciarCrono.clicked.connect(self.threadCrono)

        #Botão configurar cronometro
        self.bntConfingCronometro = QPushButton('Configurar', self)
        self.bntConfingCronometro.setGeometry(180, 650, 100, 50)
        self.bntConfingCronometro.setStyleSheet(
            'QPushButton {font: 18px; color: black; font: bold; background-color: #ECF0F1; border-radius: 10px}'
        )
        self.bntConfingCronometro.clicked.connect(self.configCronometro)

        #Seção Sortear Número
        self.labelSorteio = QLabel('Sortear Número', self)
        self.labelSorteio.setStyleSheet(
            'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}'
        )
        self.labelSorteio.setGeometry(970, 450, 200, 50)
        self.labelAte = QLabel('ATÉ', self)
        self.labelAte.setStyleSheet(
            'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}'
        )
        self.labelAte.setGeometry(1040, 520, 50, 50)
        self.spinBoxNumb1 = QSpinBox(self)
        self.spinBoxNumb2 = QSpinBox(self)
        self.spinBoxNumb1.setGeometry(940, 520, 90, 50)
        self.spinBoxNumb2.setGeometry(1100, 520, 90, 50)
        self.spinBoxNumb1.setStyleSheet('QSpinBox {font: 50px}')
        self.spinBoxNumb2.setStyleSheet('QSpinBox {font: 50px}')
        self.bntSortear = QPushButton('Sortear', self)
        self.bntSortear.setGeometry(1020, 590, 90, 50)
        self.bntSortear.setStyleSheet(
            'QPushButton {font: 25px; color: black; font: bold; background-color: #F9690E; border-radius: 10px}'
        )
        self.bntSortear.clicked.connect(self.sortearNumero)

        #Seção da janela principal
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.setWindowIcon(QtGui.QIcon("user.png"))
        self.show()

    def setValorLcd(self, n):

        if (n == 1):
            self.lcdPlacar1.display(self.spinBox.value())
            self.valorPlacarA = self.spinBox.value()

        if (n == 2):
            self.lcdPlacar2.display(self.spinBox.value())
            self.valorPlacarB = self.spinBox.value()

        def placarColor(valorPlacarA, valorPlacarB):
            if (valorPlacarA > valorPlacarB):
                self.lcdPlacar1.setStyleSheet(
                    'QLCDNumber {background-color: #3FC380; color: white; font: bold}'
                )

            if (valorPlacarB > valorPlacarA):
                self.lcdPlacar2.setStyleSheet(
                    'QLCDNumber {background-color: #3FC380; color: white; font: bold}'
                )

            if (valorPlacarA < valorPlacarB):
                self.lcdPlacar1.setStyleSheet(
                    'QLCDNumber {background-color: #F22613; color: white; font: bold}'
                )

            if (valorPlacarB < valorPlacarA):
                self.lcdPlacar2.setStyleSheet(
                    'QLCDNumber {background-color: #F22613; color: white; font: bold}'
                )

            if (valorPlacarA == valorPlacarB):
                self.lcdPlacar1.setStyleSheet(
                    'QLCDNumber {background-color: #22A7F0; color: white; font: bold}'
                )
                self.lcdPlacar2.setStyleSheet(
                    'QLCDNumber {background-color: #22A7F0; color: white; font: bold}'
                )

        placarColor(self.valorPlacarA, self.valorPlacarB)

    def bntIniciarCronoState(self):
        i = 0
        if (self.bntIniciarCrono.isChecked()):
            i += 1
            return i
        return i

    def threadCrono(self):
        global stop
        stop = 0
        bntCronoStatus = self.bntIniciarCronoState()

        if (bntCronoStatus == 1):
            self.t = threading.Thread(target=self.iniciarCrono)
            self.bntIniciarCrono.setText('PARAR')
            self.t.start()

        if (bntCronoStatus == 0):
            self.bntIniciarCrono.setText('Iniciar novamente')
            stop = -1

    def iniciarCrono(self):

        self.seg = self.cronoWindow.getValueSpinSeg()
        self.min = self.cronoWindow.getValueSpinMin()

        self.count = 0
        self.i = self.seg + (self.min * 60)

        while (self.i != 0):
            self.min = self.count / 60
            self.seg = self.count % 60 + 1
            time.sleep(1)
            self.labelCrono.setText('%02d:%02d' % (self.min, self.seg))
            self.count += 1
            self.i -= 1

            if stop == -1:
                self.bntIniciarCrono.setText('Iniciar novamente')
                self.i = 0

    def sortearNumero(self):
        try:
            a = self.spinBoxNumb1.value()
            b = self.spinBoxNumb2.value()
            self.resultado = randint(a, b)
            self.msgResultado = QMessageBox()
            self.msgResultado.setStyleSheet(
                'QMessageBox, QMessageBox QLabel {font: 35px; color: white; background-color:#34495E}'
            )
            self.msgResultado.information(
                self.msgResultado, 'INFORMAÇÃO ',
                'Número sorteado:  \n-->{:>7}        <--'.format(
                    self.resultado))
        except ValueError:
            self.warningValue = QMessageBox()
            self.warningValue.setStyleSheet(
                'QMessageBox, QMessageBox QLabel {font: bold; color: white; font: 25px; background-color: #D91E18;}'
            )
            self.warningValue.warning(
                self.warningValue, 'Aviso',
                'Entrada incorreta! \n 1 até 0 é inválido')

    def configCronometro(self):
        print('Inciando cronometro')
        self.cronoWindow = Cronometro()
        self.cronoWindow.show()
示例#28
0
class main_window(QMainWindow):
    def __init__(self, app):
        self.app = app
        self.points = 0

        #current model
        self.current_model = 0
        self.pca_model = PCA(n_components=2)

        super(main_window, self).__init__()
        #==================# MAIN WIDGET LAYOUT #==================#

        #Big window
        self.widget = QtWidgets.QWidget()
        self.setCentralWidget(self.widget)
        self.widget.setLayout(QtWidgets.QGridLayout())
        self.widget.layout().setContentsMargins(50, 10, 50, 20)
        self.widget.layout().setSpacing(10)
        self.widget.layout().setColumnStretch(0, 4)
        self.widget.layout().setColumnStretch(1, 5)
        self.widget.layout().setColumnStretch(2, 7)
        self.widget.layout().setRowStretch(0, 6)
        self.widget.layout().setRowStretch(1, 7)
        self.widget.layout().setRowStretch(2, 13)
        self.widget.layout().setRowStretch(3, 15)
        self.setWindowTitle("US Accidents Data Mining")
        self.showMaximized()
        #THEME COLOR
        self.setStyleSheet(
            "QMainWindow {background-image: url(background.jpg)}")
        print("Main window opened")

        # ==================# GROUP WIDGET LAYOUT #==================#
        # Small group0 (training)
        self.GroupBox0 = QGroupBox()
        self.layout0 = QGridLayout()
        self.GroupBox0.setLayout(self.layout0)
        self.layout0.setContentsMargins(20, 5, 20, 5)
        self.layout0.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox0, 0, 0, 2, 1)

        # Small group1 (predicting)
        self.GroupBox1 = QGroupBox()
        layout1 = QGridLayout()
        self.GroupBox1.setLayout(layout1)
        layout1.setContentsMargins(20, 5, 20, 5)
        layout1.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox1, 2, 0, 3, 1)

        #Small group (status)
        self.GroupBox_status = QGroupBox()
        self.layoutstatus = QGridLayout()
        self.GroupBox_status.setLayout(self.layoutstatus)
        self.layoutstatus.setContentsMargins(5, 5, 5, 5)
        self.layoutstatus.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox_status, 0, 1, 1, 1)

        # Small group2 (tabs)
        self.GroupBox2 = QGroupBox()
        layout2 = QGridLayout()
        self.GroupBox2.setLayout(layout2)
        layout2.setContentsMargins(5, 5, 5, 5)
        layout2.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox2, 1, 1, 2, 1)

        # Small group3 (summary of stats)
        self.GroupBox3 = QGroupBox()
        layout3 = QGridLayout()
        self.GroupBox3.setLayout(layout3)
        layout3.setContentsMargins(5, 5, 5, 5)
        layout3.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox3, 3, 1, 2, 2)

        # Small group4 (map)
        self.GroupBox4 = QGroupBox()
        self.layout4 = QGridLayout()
        self.GroupBox4.setLayout(self.layout4)
        self.layout4.setContentsMargins(5, 5, 5, 5)
        self.layout4.setSpacing(5)
        self.widget.layout().addWidget(self.GroupBox4, 0, 2, 3, 1)

        # ==================# GROUP 0 WIDGETS #==================#

        # Number of Samples
        self.num_samples = QLabel("Number of Samples:")
        self.layout0.addWidget(self.num_samples, 0, 0, 1, 1)
        self.SpinBox1 = QtWidgets.QSpinBox(self.widget)
        self.SpinBox1.setMaximum(2000000)
        self.SpinBox1.setMinimum(100)
        self.SpinBox1.setSingleStep(100)
        self.layout0.addWidget(self.SpinBox1, 0, 1, 1, 1)

        # Train Percent
        self.train_percent = QLabel("Train Split:")
        self.layout0.addWidget(self.train_percent, 1, 0, 1, 1)
        self.SpinBox2 = QtWidgets.QSpinBox(self.widget)
        self.SpinBox2.setMaximum(90)
        self.SpinBox2.setMinimum(70)
        self.SpinBox2.setSingleStep(10)
        self.SpinBox2.setSuffix("%")
        self.layout0.addWidget(self.SpinBox2, 1, 1, 1, 1)

        # Test Percent
        self.model_algorithm_label = QLabel("Algorithm:")
        self.layout0.addWidget(self.model_algorithm_label, 2, 0, 1, 1)
        self.model_algorithm_combo = QtWidgets.QComboBox(self.widget)
        self.model_algorithm_combo.addItem("Decision Trees")
        self.model_algorithm_combo.addItem("Random Forest")
        self.model_algorithm_combo.addItem("Logistic Regression")
        self.model_algorithm_combo.addItem("KNN")
        self.model_algorithm_combo.addItem("SVM")
        self.model_algorithm_combo.addItem("Naive Bayes")
        self.layout0.addWidget(self.model_algorithm_combo, 2, 1, 1, 1)

        # Model Accuracy
        self.accuracy = QLabel("Model Accuracy:")
        self.layout0.addWidget(self.accuracy, 3, 0, 1, 1)
        self.accuracy_display = QLCDNumber()
        self.accuracy_display.setMaximumHeight(50)
        self.accuracy_display.setSegmentStyle(QLCDNumber.Flat)
        self.layout0.addWidget(self.accuracy_display, 3, 1, 1, 1)

        # Train Model
        Button1 = QtWidgets.QPushButton(self.widget)
        Button1.setText("Train Model")
        Button1.clicked.connect(self.on_Button_train_clicked)
        self.layout0.addWidget(Button1, 4, 0, 1, 2)

        # ==================# GROUP 1 WIDGETS #==================#

        #Latitude
        #self.latitude = QLabel("Latitude:")
        #layout1.addWidget(self.latitude, 0, 0, 1, 1)
        #self.line_edit_latitude = QLineEdit()
        #self.line_edit_latitude.setPlaceholderText('Enter Latitude')
        #layout1.addWidget(self.line_edit_latitude, 0, 1, 1, 1)

        #Longitude
        #self.longitude = QLabel("Longitude:")
        #layout1.addWidget(self.longitude, 1, 0, 1, 1)
        #self.line_edit_longitude = QLineEdit()
        #self.line_edit_longitude.setPlaceholderText('Enter Longitude')
        #layout1.addWidget(self.line_edit_longitude, 1, 1, 1, 1)

        # Number
        # self.number = QLabel("Number:")
        # layout1.addWidget(self.number, 3, 0, 1, 1)
        # self.line_edit_number = QLineEdit()
        # self.line_edit_number.setPlaceholderText('Enter Number')
        # layout1.addWidget(self.line_edit_number, 3, 1, 1, 1)

        #Distance(mi)
        self.distance = QLabel("Distance (mi):")
        layout1.addWidget(self.distance, 2, 0, 1, 1)
        ####
        self.line_edit_distance = QtWidgets.QDoubleSpinBox(self.widget)
        self.line_edit_distance.setDecimals(4)
        self.line_edit_distance.setMaximum(100)
        self.line_edit_distance.setMinimum(0)
        self.line_edit_distance.setSingleStep(0.0001)
        self.line_edit_distance.setSuffix(" mi ")
        #self.line_edit_distance = QLineEdit()
        #self.line_edit_distance.setPlaceholderText('Enter Distance')
        layout1.addWidget(self.line_edit_distance, 2, 1, 1, 1)

        #Temperature
        self.temperature = QLabel("Temperature (F):")
        layout1.addWidget(self.temperature, 4, 0, 1, 1)
        ####
        self.line_edit_temperature = QtWidgets.QDoubleSpinBox(self.widget)
        self.line_edit_temperature.setMaximum(150)
        self.line_edit_temperature.setMinimum(-150)
        self.line_edit_temperature.setSuffix(" F  ")
        #self.line_edit_temperature = QLineEdit()
        #self.line_edit_temperature.setPlaceholderText('Enter Temperature')
        layout1.addWidget(self.line_edit_temperature, 4, 1, 1, 1)

        #Wind Chill(F)
        self.wind_chill = QLabel("Wind Chill (F):")
        layout1.addWidget(self.wind_chill, 5, 0, 1, 1)
        ####
        self.line_edit_wind_chill = QtWidgets.QSpinBox(self.widget)
        self.line_edit_wind_chill.setMaximum(150)
        self.line_edit_wind_chill.setMinimum(-150)
        self.line_edit_wind_chill.setSuffix(" F  ")
        #self.line_edit_wind_chill = QLineEdit()
        #self.line_edit_wind_chill.setPlaceholderText('Enter Wind Chill')
        layout1.addWidget(self.line_edit_wind_chill, 5, 1, 1, 1)

        #Humidity%
        self.humidity = QLabel("Humidity (%):")
        layout1.addWidget(self.humidity, 6, 0, 1, 1)
        ####
        self.line_edit_humidity = QtWidgets.QSpinBox(self.widget)
        self.line_edit_humidity.setMaximum(100)
        self.line_edit_humidity.setMinimum(0)
        self.line_edit_humidity.setSuffix(" %  ")
        #self.line_edit_humidity = QLineEdit()
        #self.line_edit_humidity.setPlaceholderText('Enter Humidity')
        layout1.addWidget(self.line_edit_humidity, 6, 1, 1, 1)

        #Pressure(in)
        self.pressure = QLabel("Pressure (in):")
        layout1.addWidget(self.pressure, 7, 0, 1, 1)
        ####
        self.line_edit_pressure = QtWidgets.QSpinBox(self.widget)
        self.line_edit_pressure.setMaximum(150)
        self.line_edit_pressure.setMinimum(0)
        self.line_edit_pressure.setSuffix(" in ")
        #self.line_edit_pressure = QLineEdit()
        #self.line_edit_pressure.setPlaceholderText('Enter Pressure')
        layout1.addWidget(self.line_edit_pressure, 7, 1, 1, 1)

        #Visibility(mi)
        self.visibility = QLabel("Visibility (mi):")
        layout1.addWidget(self.visibility, 8, 0, 1, 1)
        ####
        self.line_edit_visibility = QtWidgets.QSpinBox(self.widget)
        self.line_edit_visibility.setMaximum(100)
        self.line_edit_visibility.setMinimum(0)
        self.line_edit_visibility.setSuffix(" mi ")
        #self.line_edit_visibility = QLineEdit()
        #self.line_edit_visibility.setPlaceholderText('Enter Visibility')
        layout1.addWidget(self.line_edit_visibility, 8, 1, 1, 1)

        #Wind Speed(mph)
        self.wind_speed = QLabel("Wind Speed (mph):")
        layout1.addWidget(self.wind_speed, 9, 0, 1, 1)
        ####
        self.line_edit_wind_speed = QtWidgets.QSpinBox(self.widget)
        self.line_edit_wind_speed.setMaximum(100)
        self.line_edit_wind_speed.setMinimum(0)
        self.line_edit_wind_speed.setSuffix(" mph")
        #self.line_edit_wind_speed = QLineEdit()
        #self.line_edit_wind_speed.setPlaceholderText('Enter Wind Speed')
        layout1.addWidget(self.line_edit_wind_speed, 9, 1, 1, 1)

        #Precipitation(in)
        self.precipitation = QLabel("Precipitation (in):")
        layout1.addWidget(self.precipitation, 10, 0, 1, 1)
        ####
        self.line_edit_precipitation = QtWidgets.QDoubleSpinBox(self.widget)
        self.line_edit_precipitation.setDecimals(4)
        self.line_edit_precipitation.setMaximum(100)
        self.line_edit_precipitation.setMinimum(0)
        self.line_edit_precipitation.setSingleStep(0.0001)
        self.line_edit_precipitation.setSuffix(" in ")
        #self.line_edit_precipitation = QLineEdit()
        #self.line_edit_precipitation.setPlaceholderText('Enter Precipitation')
        layout1.addWidget(self.line_edit_precipitation, 10, 1, 1, 1)

        # Severity
        self.severity = QLabel("Severity Prediction:")
        layout1.addWidget(self.severity, 11, 0, 1, 1)
        self.severity_display = QLCDNumber()
        self.severity_display.setMaximumHeight(50)
        self.severity_display.setSegmentStyle(QLCDNumber.Flat)
        layout1.addWidget(self.severity_display, 11, 1, 1, 1)

        # predict button
        Button_predict = QtWidgets.QPushButton(self.widget)
        Button_predict.setText("Predict Severity of Accident")
        Button_predict.clicked.connect(self.on_Button_predict_clicked)
        layout1.addWidget(Button_predict, 12, 0, 1, 2)

        # ==================# GROUP STATUS WIDGETS (STATUS LAYOUT) #==================#

        self.status_label_model = QPushButton(self.widget)
        self.status_label_model.setText("VIEW CURRENT MODEL")
        self.status_label_model.clicked.connect(self.on_Button_model_clicked)
        self.layoutstatus.addWidget(self.status_label_model, 0, 0, 1, 1)
        self.status_display_model = QLabel("NO MODEL")
        self.status_display_model.setStyleSheet(
            "QLabel { color: red ; font-weight: bold}")
        self.layoutstatus.addWidget(self.status_display_model, 1, 0, 1, 1)

        self.status_map = QPushButton(self.widget)
        self.status_map.setText("VIEW GEOMAP STATUS")
        self.status_map.clicked.connect(self.on_Button_geomap_clicked)
        self.layoutstatus.addWidget(self.status_map, 0, 1, 1, 1)
        self.status_display_map = QLabel("WAIT...")
        self.status_display_map.setStyleSheet(
            "QLabel { color: yellow ; font-weight: bold}")
        self.layoutstatus.addWidget(self.status_display_map, 1, 1, 1, 1)

        # ==================# GROUP 2 WIDGETS (TABS WIDGET LAYOUT) #==================#
        #Tabs
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab0 = QWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        #self.tabs.resize(300, 200)

        # Add tabs
        # tab0
        self.tabs.addTab(self.tab0, "Correlogram")
        tab0_layout = QVBoxLayout(self)
        self.tab0.setLayout(tab0_layout)

        #tab1
        self.tabs.addTab(self.tab1, "Histograms")
        tab1_layout = QVBoxLayout(self)
        self.tab1.setLayout(tab1_layout)

        # tab2
        self.tabs.addTab(self.tab2, "Scatterplots")
        self.tab2_layout = QVBoxLayout(self)
        self.tab2.setLayout(self.tab2_layout)

        # tab3
        self.tabs.addTab(self.tab3, "Test Set")
        self.tab3_layout = QVBoxLayout(self)
        self.tab3.setLayout(self.tab3_layout)

        # Add tabs to widget
        layout2.addWidget(self.tabs)

        # ==================# INDIVIDUAL TAB WIDGETS (INSIDE GROUP 2)#==================#
        # CORRELATION
        self.imageView0 = QLabel(self.widget)
        self.pixmap0 = QPixmap("analysis.png")
        self.imageView0.setPixmap(self.pixmap0)
        # scroller
        # self.scroll = QtWidgets.QScrollArea(self.widget)
        # self.scroll.setWidget(self.imageView)
        tab0_layout.addWidget(self.imageView0)

        # HISTOGRAMS
        self.imageView = QLabel(self.widget)
        self.pixmap = QPixmap("longblank.png")
        self.imageView.setPixmap(self.pixmap)
        # scroller
        self.scroll = QtWidgets.QScrollArea(self.widget)
        self.scroll.setWidget(self.imageView)
        self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll.widgetResizable()
        tab1_layout.addWidget(self.scroll)

        #SCATTER
        self.imageView2 = QLabel(self.widget)
        self.pixmap2 = QPixmap("longblank.png")
        self.imageView2.setPixmap(self.pixmap2)
        # scroller
        self.scroll2 = QtWidgets.QScrollArea(self.widget)
        self.scroll2.setWidget(self.imageView2)
        self.scroll2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll2.widgetResizable()
        self.tab2_layout.addWidget(self.scroll2)

        #TEST SET
        filename_test_set = os.path.expanduser(
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), "X_test.csv")))
        self.items_test_set = []
        self.filename_test_set = filename_test_set
        self.model_test_set = QtGui.QStandardItemModel(self.widget)
        self.model_test_set.setHorizontalHeaderLabels([
            "Distance(mi)", "Temperature(F)", "Wind_Chill(F)", "Humidity(%)",
            "Pressure(in)", "Visibility(mi)", "Wind_Speed(mph)",
            "Precipitation(in)", "Severity", "Prediction"
        ])
        self.tableView_test_set = QTableView(self.widget)
        # self.tableView.setStyleSheet("QTableView{ background-color: rgb(45, 45, 45);  }")  # cell color
        self.tableView_test_set.horizontalHeader().setStretchLastSection(True)
        self.tableView_test_set.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.tableView_test_set.setModel(self.model_test_set)
        self.tab3_layout.addWidget(self.tableView_test_set)

        # ==================# GROUP 3 WIDGETS (TABLE DATABASE) #==================#
        filename = os.path.expanduser(
            os.path.abspath(
                os.path.join(os.path.dirname(__file__),
                             "statistic_summary.csv")))
        self.items = []
        self.fileName = filename
        #self.on_Button1_clicked

        self.model = QtGui.QStandardItemModel(self.widget)

        self.model.setHorizontalHeaderLabels(
            ['Count', 'Mean', 'Std', 'Min', '25%', '50%', '75%', 'Max'])
        self.model.setVerticalHeaderLabels([
            'Severity', 'Latitude', 'Longitude', 'Distance(mi)', 'Number',
            'Temperature', 'Wind Chill(F)', 'Humidity%', 'Pressure(in)',
            'Visibility(mi)', 'Wind Speed(mph)                   ',
            'Precipitation(in)'
        ])
        self.tableView = QTableView(self.widget)
        #self.tableView.setStyleSheet("QTableView{ background-color: rgb(45, 45, 45);  }")  # cell color
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.tableView.setModel(self.model)
        layout3.addWidget(self.tableView, 1, 0, 1, 4)

        # ==================# GROUP 4 WIDGETS (MAP) #==================#
        # Qwebview maps
        #create map instance and update later when the train button is clicked
        self.map = 0
        self.create_map_instance()
        self.layout4.addWidget(self.map)

        # ==================# SHOW EVERYTHING #==================#
        self.show()

        # make map ready message
        self.app.processEvents()
        msg = QMessageBox()
        msg.setText("<p align = 'center'>"
                    "<i><br>(US Accidents Dataset)</i><br>"
                    "<h2>DATA ANALYSIS &<br>"
                    "DATA VISUALIZATION TOOL w/<br> "
                    "GEOGRAPHICAL MAPPING</h2>"
                    "<br>"
                    "<i>Introduction to Data Mining</i><br>"
                    "<i>(DATS 6103)</i><br>"
                    "<i>Professor: Amir Jafari, PhD</i></h6><br>"
                    ""
                    "</p>")
        msg.exec_()

        self.app.processEvents()
        time.sleep(4)
        self.status_display_map.setText("NO DATA POINTS")
        self.status_display_map.setStyleSheet(
            "QLabel { color: red ; font-weight: bold}")
        self.status_display_map.update()

#########################################   FUNCTIONS   #####################################################

#=============== VIEW STATISTICAL SUMMRY FUNCTION ====================#
# @QtCore.pyqtSlot()
#def on_Button1_clicked(self):
#self.loadCsv(self.fileName)
#print("Statistical summary button clicked")

    def loadCsv(self, fileName):
        while (self.model.rowCount() > 0):
            self.model.removeRow(0)
        try:
            with open(fileName, "r") as fileInput:
                for row in csv.reader(fileInput):
                    self.items = [QtGui.QStandardItem(field) for field in row]
                    self.model.appendRow(self.items)
            self.model.setVerticalHeaderLabels([
                'Severity', 'Latitude', 'Longitude', 'Distance(mi)', 'Number',
                'Temperature', 'Wind Chill(F)', 'Humidity%', 'Pressure(in)',
                'Visibility(mi)', 'Wind Speed(mph)                   ',
                'Precipitation(in)'
            ])
        except:
            self.model.setVerticalHeaderLabels([
                'Severity', 'Latitude', 'Longitude', 'Distance(mi)', 'Number',
                'Temperature', 'Wind Chill(F)', 'Humidity%', 'Pressure(in)',
                'Visibility(mi)', 'Wind Speed(mph)                   ',
                'Precipitation(in)'
            ])
            print("No Database")

    # =============== VIEW TEST SET FUNCTION ====================#

    def loadCsv_test_set(self, fileName):
        while (self.model_test_set.rowCount() > 0):
            self.model_test_set.removeRow(0)
        try:
            with open(fileName, "r") as fileInput:
                csvreader = csv.reader(fileInput)
                for row in csvreader:
                    print("row is", row)
                    self.items_test_set = [
                        QtGui.QStandardItem(field) for field in row
                    ]
                    self.model_test_set.appendRow(self.items_test_set)
        except:
            print("No Database on test set")

    #====================== GET ATTRIBUTES  FUNCTION=========================#

    def get_predict_attributes(self):
        print(
            "Data in predict button is: ",
            #self.severity_display.text(),
            #self.line_edit_latitude.text(),
            #self.line_edit_longitude.text(),
            #self.line_edit_number.text(),
            self.line_edit_distance.text(),
            self.line_edit_temperature.text(),
            self.line_edit_wind_chill.text(),
            self.line_edit_humidity.text(),
            self.line_edit_pressure.text(),
            self.line_edit_visibility.text(),
            self.line_edit_wind_speed.text(),
            self.line_edit_precipitation.text())
        return [
            # self.severity_display.text(),
            #self.line_edit_latitude.text(),
            #self.line_edit_longitude.text(),
            #self.line_edit_number.text(),
            self.line_edit_distance.text(),
            self.line_edit_temperature.text(),
            self.line_edit_wind_chill.text(),
            self.line_edit_humidity.text(),
            self.line_edit_pressure.text(),
            self.line_edit_visibility.text(),
            self.line_edit_wind_speed.text(),
            self.line_edit_precipitation.text()
        ]

    def get_train_attributes(self):
        print(
            "Data in train button is: ",
            self.SpinBox1.text(),
            self.SpinBox2.text(),
            self.model_algorithm_combo.currentText(),
            #self.accuracy_display.text()
        )
        return (
            self.SpinBox1.text(),
            self.SpinBox2.text(),
            self.model_algorithm_combo.currentText(),
            # self.accuracy_display.text()
        )

    #########-------------------------------------- INITIALIZE MAP FUNCTION -------------------------------------- #########
    def create_map_instance(self):

        # create Qwebview Map instance
        try:
            import map_view
        except:
            print("import exception")

        # create initial dummy data for map
        # initial self.points is 0
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "map.html"))
        self.map = map_view.map_webview(file_path,
                                        self.points)  # pass datapoints

    #########-------------------------------------- TRAIN FUNCTION -------------------------------------- #########
    def on_Button_train_clicked(self):
        print("Button train clicked")
        attributes_train = self.get_train_attributes()
        submit_status = True
        k_value = 0

        if attributes_train[2] == "KNN":
            # pop up screen
            try:
                import pop_up_entry
            except:
                print("import error")
            pop_up1 = pop_up_entry.pop_up_entry(self.app, attributes_train[2])
            k_value, submit_status = pop_up1.get_status()
            print(k_value)
            print(submit_status)

        if submit_status == True:
            #make stus bar busy
            self.update_status_bar()
            self.app.processEvents()

            # train model
            try:
                import train_model
            except:
                print("import exception")
            model1 = train_model.train(attributes_train, k_value, self.app,
                                       self.pca_model)
            self.points = model1.get_map_data_points()
            self.current_model = model1.get_model()

            #update screen
            self.accuracy_display.display(
                model1.get_model_accuracy())  # set the lcd accuract digit
            self.update_screen_widgets(attributes_train)

            #make model ready message
            self.app.processEvents()
            msg = QMessageBox()
            msg.setText('Model Ready')
            msg.exec_()

            try:
                import map_load_time
            except:
                print("import exception")

            numsamples = int(attributes_train[0])
            loadtime1 = map_load_time.map_load_time()
            timetoloadmap = loadtime1.calculate_load_time(numsamples)

            # make map ready after a few seconds depending on sample size
            self.app.processEvents()
            time.sleep(int(timetoloadmap))
            self.status_display_map.setText("READY")
            self.status_display_map.setStyleSheet(
                "QLabel { color: green ; font-weight: bold}")
            self.status_display_map.update()

            # make map ready message
            self.app.processEvents()
            msg = QMessageBox()
            msg.setText('Geo Map Ready')
            msg.exec_()

    def update_status_bar(self):
        self.status_display_model.setText("WAIT...")
        self.status_display_model.setStyleSheet(
            "QLabel { color: yellow ; font-weight: bold}")
        self.status_display_model.update()
        self.status_display_map.setText("WAIT...")
        self.status_display_map.setStyleSheet(
            "QLabel { color: yellow ; font-weight: bold}")
        self.status_display_map.update()

    def update_screen_widgets(self, attributes_train):
        # update image in screen correlation
        self.pixmap0 = QPixmap("correlation_matrix.png")
        self.imageView0.setPixmap(self.pixmap0)
        self.imageView0.update()

        # update image in screen histograms
        self.pixmap = QPixmap("histograms.png")
        self.imageView.setPixmap(self.pixmap)
        self.imageView.update()
        self.scroll.update()

        # update image in screen scatter
        self.pixmap2 = QPixmap("scatterplots.png")
        self.imageView2.setPixmap(self.pixmap2)
        self.imageView2.update()
        self.scroll2.update()

        # update image in screen graphs
        #self.pixmap3 = QPixmap("temp_hist.png")
        #self.imageView3.setPixmap(self.pixmap3)
        #self.imageView3.update()

        # update map
        self.layout4.removeWidget(self.map)
        self.create_map_instance()
        # self.map.update()
        self.layout4.addWidget(self.map)

        # update summary table
        filename = os.path.expanduser(
            os.path.abspath(
                os.path.join(os.path.dirname(__file__),
                             "statistic_summary.csv")))
        self.items = []
        self.fileName = filename
        self.loadCsv(self.fileName)

        # update test set table
        filename_test_set = os.path.expanduser(
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), "X_test.csv")))
        self.items_test_set = []
        self.fileName_test_set = filename_test_set
        self.loadCsv_test_set(self.fileName_test_set)

        #update lcd train (accuracy
        #self.accuracy_display.setStyleSheet("QLCDNumber { color: black ; background-color: #1f77b4 }")
        self.accuracy_display.update()

        # update lcd predict (severity)
        self.severity_display.display(0)
        self.severity_display.update()

        #status bar update
        self.status_display_model.setText(attributes_train[2].upper())
        self.status_display_model.setStyleSheet(
            "QLabel { color: green ; font-weight: bold}")
        self.status_display_model.update()
        self.status_display_map.setText("WAIT...")
        self.status_display_map.setStyleSheet(
            "QLabel { color: yellow ; font-weight: bold}")
        self.status_display_map.update()

    #########-------------------------------------- PREDICT FUNCTION -------------------------------------- #########
    def on_Button_predict_clicked(self):
        model_name = self.get_train_attributes()
        print("Button predict clicked")
        attributes = self.get_predict_attributes()
        print("button predcit", attributes)
        print("button predcit", self.current_model)

        #make sure there is a model and there are no missing values
        if self.current_model == 0:
            print("missing model", self.current_model)
            msg = QMessageBox()
            msg.setText('No Model Available')
            msg.exec_()
        elif "" in attributes:
            print("missing values", attributes)
            msg = QMessageBox()
            msg.setText('Missing Values')
            msg.exec_()
        else:
            ###predict the inputs with the current model
            try:
                import predict
            except:
                print("import exception")
            predict1 = predict.predict(attributes, self.current_model,
                                       self.status_display_model.text(),
                                       model_name[2], self.pca_model)
            predict_result1 = predict1.predict_inputs()
            self.severity_display.display(predict_result1)

            #print("no model or missing inputs")

    #########-------------------------------------- VIEW GEOMAP LOAD TIME PNG FUNCTION -------------------------------------- #########
    def on_Button_geomap_clicked(self):
        display_img = QDialog()
        label_image = QLabel()
        pixmap1 = QPixmap('map_load_time.png')
        label_image.setPixmap(pixmap1)
        layout_show = QGridLayout()
        display_img.setLayout(layout_show)
        layout_show.addWidget(label_image, 0, 0)
        display_img.exec_()

        #msg = QMessageBox()
        #msg.setIconPixmap(QPixmap("map_load_time.png"))
        #msg.exec_()
        print("geobuttonmap clicked")

    #########-------------------------------------- VIEW ML MODEL PNG FUNCTION -------------------------------------- #########
    def on_Button_model_clicked(self):
        display_img = QDialog()
        label_image = QLabel()
        if self.current_model == 0:
            msg = QMessageBox()
            msg.setText('No Model Available')
            msg.exec_()
            #pixmap1 = QPixmap('analysis.png')
        else:
            pixmap1 = QPixmap('model_image.png')

            label_image.setPixmap(pixmap1)
            layout_show = QGridLayout()
            display_img.setLayout(layout_show)

            # scroller
            #scroll = QtWidgets.QScrollArea()
            #scroll.setWidget(label_image)
            #layout_show.addWidget(scroll, 0, 0)

            layout_show.addWidget(label_image, 0, 0)
            display_img.exec_()

        print("model button clicked")
示例#29
0
    def __init__(self):
        super(SplendorWindow, self).__init__()
        self.setWindowTitle("Splendor")
        self.resize(950, 670)

        self.board = SplendorBoard()
        layout = QGridLayout()
        self.game_table = SplendorTable()
        layout_cards = QGridLayout()
        layout_chips = QGridLayout()
        layout_lords = QGridLayout()
        scoreLcd = QLCDNumber(2)
        scoreLcd.setSegmentStyle(QLCDNumber.Filled)

        layout.addWidget(self.createLabel("Name: "), 0, 0)
        layout.addWidget(self.createLabel("Sandy"), 0, 1)
        layout.addWidget(self.createLabel("Score: "), 0, 2)
        layout.addWidget(scoreLcd, 0, 3)

        self.frame_cards = QFrame()
        self.frame_cards.setFrameStyle(QFrame.Box | QFrame.Raised)
        self.frame_cards.setLayout(layout_cards)

        self.frame_chips = QFrame()
        self.frame_chips.setFrameStyle(QFrame.Box | QFrame.Raised)
        frame_lords = QFrame()
        frame_lords.setFrameStyle(QFrame.Box | QFrame.Raised)

        layout.addWidget(self.frame_cards, 2, 0, 4, 5)
        layout.addWidget(self.frame_chips, 2, 6, 4, 2)
        #layout.addWidget(frame_lords, 2, 10)

        self.frame_chips.setLayout(layout_chips)
        frame_lords.setLayout(layout_lords)

        for r in (0, 4, 8):
            row = self.game_table.state[int(r / 4)]
            bord_line_cards = []
            indent = 0
            for i in range(4):
                card = row[i]
                bord_line_cards.append(self.createCardSelector(card, self.frame_cards))

                layout_cards.addWidget(self.createCard(card, self.frame_cards), 0 + r, indent, 3, 2)
                layout_cards.addWidget(bord_line_cards[i], 3 + r, indent)
                indent += 2
        self.setLayout(layout)

        rr = 0
        for r in (0, 2, 4):
            row = self.game_table.state[int(r / 2)]
            bord_line_chips = []
            indent = 0
            for i in range(2):
                chip = row[4 + i]
                bord_line_chips.append(self.createChipSelector(chip, self.frame_chips))

                layout_chips.addWidget(self.createChip(chip, self.frame_chips), 0 + rr, 0, 4, 2)
                layout_chips.addWidget(bord_line_chips[i], 2 + rr, 0)
                rr += 2
        self.setLayout(layout)
示例#30
0
class CueWidget(QWidget):

    STOP = QIcon.fromTheme('led-off')
    START = QIcon.fromTheme('led-running')
    PAUSE = QIcon.fromTheme('led-pause')
    ERROR = QIcon.fromTheme('led-error')

    ICON_SIZE = 14

    context_menu_request = pyqtSignal(object, QPoint)
    edit_request = pyqtSignal(object)
    cue_executed = pyqtSignal(object)

    def __init__(self, cue, **kwargs):
        super().__init__(**kwargs)
        self.cue = None

        self._selected = False
        self._accurate_timing = False
        self._show_dbmeter = False
        self._countdown_mode = True

        self._dbmeter_element = None
        self._fade_element = None

        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setLayout(QGridLayout())

        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(2)
        self.layout().setColumnStretch(0, 6)
        self.layout().setRowStretch(0, 4)

        self.nameButton = QClickLabel(self)
        self.nameButton.setObjectName('ButtonCueWidget')
        self.nameButton.setWordWrap(True)
        self.nameButton.setAlignment(Qt.AlignCenter)
        self.nameButton.setFocusPolicy(Qt.NoFocus)
        self.nameButton.clicked.connect(self._clicked)
        self.nameButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.layout().addWidget(self.nameButton, 0, 0)

        self.statusIcon = QLabel(self.nameButton)
        self.statusIcon.setStyleSheet('background-color: transparent')
        self.statusIcon.setPixmap(CueWidget.STOP.pixmap(CueWidget.ICON_SIZE,
                                                        CueWidget.ICON_SIZE))

        self.seekSlider = QClickSlider(self.nameButton)
        self.seekSlider.setOrientation(Qt.Horizontal)
        self.seekSlider.setFocusPolicy(Qt.NoFocus)
        self.seekSlider.setVisible(False)

        self.dbMeter = QDbMeter(self)
        self.dbMeter.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.dbMeter.setVisible(False)

        self.timeBar = QProgressBar(self)
        self.timeBar.setTextVisible(False)
        self.timeBar.setLayout(QHBoxLayout())
        self.timeBar.layout().setContentsMargins(0, 0, 0, 0)
        self.timeDisplay = QLCDNumber(self.timeBar)
        self.timeDisplay.setStyleSheet('background-color: transparent')
        self.timeDisplay.setSegmentStyle(QLCDNumber.Flat)
        self.timeDisplay.setDigitCount(8)
        self.timeDisplay.display('00:00:00')
        self.timeBar.layout().addWidget(self.timeDisplay)
        self.timeBar.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.timeBar.setVisible(False)

        self._set_cue(cue)

    @property
    def selected(self):
        return self._selected

    @selected.setter
    def selected(self, value):
        self._selected = value
        self._update_style(self.cue.stylesheet)

    def contextMenuEvent(self, event):
        self.context_menu_request.emit(self, event.globalPos())

    def mouseMoveEvent(self, event):
        if (event.buttons() == Qt.LeftButton and
                (event.modifiers() == Qt.ControlModifier or
                 event.modifiers() == Qt.ShiftModifier)):
            mime_data = QMimeData()
            mime_data.setText(PageWidget.DRAG_MAGIC)

            drag = QDrag(self)
            drag.setMimeData(mime_data)
            drag.setPixmap(self.grab(self.rect()))

            if event.modifiers() == Qt.ControlModifier:
                drag.exec_(Qt.MoveAction)
            else:
                drag.exec_(Qt.CopyAction)

            event.accept()
        else:
            event.ignore()

    def set_countdown_mode(self, mode):
        self._countdown_mode = mode
        self._update_time(self.cue.current_time())

    def set_accurate_timing(self, enable):
        self._accurate_timing = enable
        if self.cue.state == CueState.Pause:
            self._update_time(self.cue.current_time(), True)
        elif self.cue.state != CueState.Running:
            self._update_duration(self.cue.duration)

    def show_seek_slider(self, visible):
        self.seekSlider.setVisible(visible)
        self.update()

    def show_dbmeters(self, visible):
        if isinstance(self.cue, MediaCue):
            self._show_dbmeter = visible

            if self._dbmeter_element is not None:
                self._dbmeter_element.level_ready.disconnect(self.dbMeter.plot)
                self._dbmeter_element = None

            if visible:
                self._dbmeter_element = self.cue.media.element('DbMeter')
                if self._dbmeter_element is not None:
                    self._dbmeter_element.level_ready.connect(self.dbMeter.plot)

                self.layout().addWidget(self.dbMeter, 0, 1)
                self.layout().setColumnStretch(1, 1)
                self.dbMeter.show()
            else:
                self.dbMeter.hide()
                self.layout().setColumnStretch(1, 0)

            self.update()

    def _set_cue(self, cue):
        self.cue = cue
        self.cue.changed('name').connect(self._update_name, Connection.QtQueued)
        self.cue.changed('stylesheet').connect(self._update_style, Connection.QtQueued)
        self.cue.changed('duration').connect(self._update_duration, Connection.QtQueued)
        self.cue.changed('description').connect(self._update_description, Connection.QtQueued)

        if isinstance(cue, MediaCue):
            self.cue.media.changed('pipe').connect(self._media_updated)

            self.cue.paused.connect(self.dbMeter.reset, Connection.QtQueued)
            self.cue.stopped.connect(self.dbMeter.reset, Connection.QtQueued)
            self.cue.end.connect(self.dbMeter.reset, Connection.QtQueued)
            self.cue.error.connect(self.dbMeter.reset, Connection.QtQueued)

            self.seekSlider.sliderMoved.connect(self.cue.media.seek)
            self.seekSlider.sliderJumped.connect(self.cue.media.seek)

        # Cue status changed
        self.cue.started.connect(self._status_playing, Connection.QtQueued)
        self.cue.stopped.connect(self._status_stopped, Connection.QtQueued)
        self.cue.paused.connect(self._status_paused, Connection.QtQueued)
        self.cue.error.connect(self._status_error, Connection.QtQueued)
        self.cue.end.connect(self._status_stopped, Connection.QtQueued)

        self._cue_time = CueTime(self.cue)
        self._cue_time.notify.connect(self._update_time)

        self._update_name(cue.name)
        self._update_style(cue.stylesheet)
        self._update_duration(self.cue.duration)

    def _media_updated(self):
        self.show_dbmeters(self._show_dbmeter)

        new_fade = self.cue.media.element('Fade')
        if new_fade is not self._fade_element:
            if self._fade_element is not None:
                self._fade_element.enter_fadein.disconnect(self._enter_fadein)
                self._fade_element.enter_fadeout.disconnect(self._enter_fadeout)
                self._fade_element.exit_fadein.disconnect(self._exit_fade)
                self._fade_element.exit_fadeout.disconnect(self._exit_fade)

            if new_fade is not None:
                self._fade_element = new_fade
                self._fade_element.enter_fadein.connect(self._enter_fadein)
                self._fade_element.enter_fadeout.connect(self._enter_fadeout)
                self._fade_element.exit_fadein.connect(self._exit_fade)
                self._fade_element.exit_fadeout.connect(self._exit_fade)

    def _update_name(self, name):
        self.nameButton.setText(name)

    def _update_description(self, description):
        self.nameButton.setToolTip(description)

    def _clicked(self, event):
        if not self.seekSlider.geometry().contains(event.pos()):
            if event.button() != Qt.RightButton:
                if event.modifiers() == Qt.ShiftModifier:
                    self.edit_request.emit(self.cue)
                elif event.modifiers() == Qt.ControlModifier:
                    self.selected = not self.selected
                else:
                    self.cue_executed.emit(self.cue)
                    self.cue.execute()

    def _update_style(self, stylesheet):
        stylesheet += 'text-decoration: underline;' if self.selected else ''
        self.nameButton.setStyleSheet(stylesheet)

    def _enter_fadein(self):
        p = self.timeDisplay.palette()
        p.setColor(p.WindowText, QColor(0, 255, 0))
        self.timeDisplay.setPalette(p)

    def _enter_fadeout(self):
        p = self.timeDisplay.palette()
        p.setColor(p.WindowText, QColor(255, 50, 50))
        self.timeDisplay.setPalette(p)

    def _exit_fade(self):
        self.timeDisplay.setPalette(self.timeBar.palette())

    def _status_stopped(self):
        self.statusIcon.setPixmap(CueWidget.STOP.pixmap(CueWidget.ICON_SIZE,
                                                        CueWidget.ICON_SIZE))
        self._update_time(0, True)

    def _status_playing(self):
        self.statusIcon.setPixmap(CueWidget.START.pixmap(CueWidget.ICON_SIZE,
                                                         CueWidget.ICON_SIZE))

    def _status_paused(self):
        self.statusIcon.setPixmap(CueWidget.PAUSE.pixmap(CueWidget.ICON_SIZE,
                                                         CueWidget.ICON_SIZE))

    def _status_error(self, cue, error, details):
        self.statusIcon.setPixmap(CueWidget.ERROR.pixmap(CueWidget.ICON_SIZE,
                                                         CueWidget.ICON_SIZE))
        QDetailedMessageBox.dcritical(self.cue.name, error, details)

    def _update_duration(self, duration):
        # Update the maximum values of seek-slider and time progress-bar
        if duration > 0:
            if not self.timeBar.isVisible():
                self.layout().addWidget(self.timeBar, 1, 0, 1, 2)
                self.layout().setRowStretch(1, 1)
                self.timeBar.show()
            self.timeBar.setMaximum(duration)
            self.seekSlider.setMaximum(duration)
        else:
            self.timeBar.hide()
            self.layout().setRowStretch(1, 0)

        # If not in playing or paused update the widget showed time
        if self.cue.state != CueState.Running or self.cue.state != CueState.Running:
            self._update_time(duration, True)

    def _update_time(self, time, ignore_visibility=False):
        if ignore_visibility or not self.visibleRegion().isEmpty():
            # If the given value is the duration or < 0 set the time to 0
            if time == self.cue.duration or time < 0:
                time = 0

            # Set the value the seek slider
            self.seekSlider.setValue(time)

            # If in count-down mode the widget will show the remaining time
            if self._countdown_mode:
                time = self.cue.duration - time

            # Set the value of the timer progress-bar
            if self.cue.duration > 0:
                self.timeBar.setValue(time)

            # Show the time in the widget
            self.timeDisplay.display(strtime(time, accurate=self._accurate_timing))

    def resizeEvent(self, event):
        self.update()

    def update(self):
        super().update()
        self.layout().activate()

        xdim = self.nameButton.width()
        ydim = self.nameButton.height() / 5
        ypos = self.nameButton.height() - ydim

        self.seekSlider.setGeometry(0, ypos, xdim, ydim)
        self.statusIcon.setGeometry(4, 4, CueWidget.ICON_SIZE,
                                    CueWidget.ICON_SIZE)
示例#31
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.timer = QTimer(self)
        self.formatted_time = FormattedTime(0, 0, 0)
        self.state = TimerState.INACTIVE
        self.splits = []
        self.init_menus()
        self.init_UI()

    def init_menus(self):

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')

        exitAct = QAction(QIcon('exit.png'), '&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(qApp.quit)

        fileMenu.addAction(exitAct)

        viewMenu = menubar.addMenu('View')

        viewStatAct = QAction('View statusbar', self, checkable=True)
        viewStatAct.setStatusTip('View statusbar')
        viewStatAct.setChecked(True)
        viewStatAct.triggered.connect(self.toggle_menu)

        viewMenu.addAction(viewStatAct)

    def init_UI(self):

        wid = QWidget(self)
        self.setCentralWidget(wid)

        QToolTip.setFont(QFont('SansSerif', 10))

        # ---

        self.start_stop_button = QPushButton('Start')
        self.start_stop_button.clicked.connect(self.start_stop)

        # ---

        self.pause_button = QPushButton('Pause')
        self.pause_button.resize(self.pause_button.sizeHint())
        self.pause_button.clicked.connect(self.pause_timer)
        self.pause_button.setEnabled(False)

        # ---

        self.split_button = QPushButton("Split")
        self.split_button.clicked.connect(self.split)
        self.split_button.setEnabled(False)

        # ---

        self.lcd = QLCDNumber(self)
        self.lcd.setMinimumSize(QSize(150, 150))
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.setDigitCount(len(str(self.formatted_time)))
        self.lcd.display(str(self.formatted_time))

        # ---

        self.splits_table = QTableWidget()
        self.splits_table.setMinimumSize(QSize(150, 200))
        self.splits_table.setRowCount(len(self.splits))
        self.splits_table.setColumnCount(1)
        self.splits_table.setShowGrid(False)
        self.splits_table.verticalHeader().setDefaultSectionSize(20)
        self.splits_table.verticalHeader().setVisible(False)
        self.splits_table.horizontalHeader().setVisible(False)
        self.update_splits_table()

        # ---

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.splits_table)
        vbox.addWidget(self.start_stop_button)
        vbox.addWidget(self.pause_button)
        vbox.addWidget(self.split_button)

        wid.setLayout(vbox)

        # ---

        self.statusBar().showMessage("")
        self.setGeometry(350, 300, 350, 150)
        self.setWindowTitle('Timer')
        self.setWindowIcon(QIcon('web.png'))

        self.show()

    def start_stop(self):
        if self.state == TimerState.ACTIVE:
            self.state = TimerState.INACTIVE
            self.timer.stop()
            self.sender().setText("Start")
            self.split_button.setEnabled(False)
            self.pause_button.setEnabled(False)
            self.statusBar().showMessage("Timer stopped!")
        elif self.state == TimerState.INACTIVE:
            self.state = TimerState.ACTIVE
            self.reset_timer()
            self.begin_timer()
            self.sender().setText("Stop")
            self.split_button.setEnabled(True)
            self.pause_button.setEnabled(True)
            self.statusBar().showMessage("Timer started!")
        elif self.state == TimerState.PAUSED:
            self.sender().setText("Stop")
            self.state = TimerState.ACTIVE
            self.pause_button.setEnabled(True)
            self.split_button.setEnabled(True)
            self.begin_timer()

    def pause_timer(self):
        self.statusBar().showMessage("Paused!")
        self.start_stop_button.setText("Start")
        self.formatted_time.pause()
        self.pause_button.setEnabled(False)
        self.state = TimerState.PAUSED
        self.timer.stop()

    def split(self):
        now = FormattedTime(self.formatted_time.minutes,
                            self.formatted_time.seconds,
                            self.formatted_time.centiseconds)

        self.splits.append(now)
        self.update_splits_table()

    def update_current_time(self):
        self.formatted_time.increment_time()
        self.lcd.setDigitCount(len(self.formatted_time))
        self.lcd.display(str(self.formatted_time))

    def begin_timer(self):
        self.timer.start(10)
        self.timer.timeout.connect(self.update_current_time)

    def update_splits_table(self):
        row = 0
        for split in self.splits:
            self.item = QTableWidgetItem(str(split))
            self.splits_table.setRowCount(len(self.splits))
            self.splits_table.setItem(row, 0, self.item)
            row = row + 1
        pass

    def reset_timer(self):
        self.splits = []
        self.splits_table.clear()
        self.formatted_time = FormattedTime(0, 0, 0)

    def quit_app(self):
        sys.exit()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        self.statusBar().showMessage('Moved!')

    def toggle_menu(self, state):
        if state:
            self.statusBar().show()
        else:
            self.statusBar().hide()

    def closeEvent(self, event):

        if self.state == TimerState.ACTIVE or self.state == TimerState.PAUSED:
            reply = QMessageBox.question(
                self, 'Message',
                "Timer running. Are you sure you want to quit?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            event.accept() if reply == QMessageBox.Yes else event.ignore()
        else:
            event.accept()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Space:
            if self.state == TimerState.INACTIVE:
                self.start_stop()
            else:
                self.pause_timer()
class PlayingMediaWidget(QWidget):

    def __init__(self, cue, **kwargs):
        super().__init__(**kwargs)

        self.cue = cue
        self.cue_time = CueTime(cue)
        self.cue_time.notify.connect(self._time_updated, Connection.QtQueued)

        self._dbmeter_element = None
        self._accurate_time = False

        scroll_size = (self.parent().verticalScrollBar().width() + 5)
        self.setGeometry(0, 0, self.parent().width() - scroll_size, 102)
        self.setFocusPolicy(Qt.NoFocus)

        self.gridLayoutWidget = QWidget(self)
        self.gridLayoutWidget.setGeometry(self.geometry())
        self.gridLayout = QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(2, 2, 2, 2)

        self.nameLabel = QLabel(self.gridLayoutWidget)
        self.nameLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.nameLabel.setText(cue.name)
        self.nameLabel.setToolTip(cue.name)
        self.gridLayout.addWidget(self.nameLabel, 0, 0, 1, 3)

        self.playPauseButton = QPushButton(self.gridLayoutWidget)
        self.playPauseButton.setSizePolicy(QSizePolicy.Ignored,
                                           QSizePolicy.Ignored)
        self.playPauseButton.setIcon(QIcon.fromTheme('media-playback-pause'))
        self.playPauseButton.setIconSize(QSize(24, 24))
        self.playPauseButton.setFocusPolicy(Qt.NoFocus)
        self.playPauseButton.clicked.connect(self._pause)
        self.gridLayout.addWidget(self.playPauseButton, 1, 0)

        self.stopButton = QPushButton(self.gridLayoutWidget)
        self.stopButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.stopButton.setIcon(QIcon.fromTheme('media-playback-stop'))
        self.stopButton.setIconSize(QSize(24, 24))
        self.stopButton.setFocusPolicy(Qt.NoFocus)
        self.stopButton.clicked.connect(self._stop)
        self.gridLayout.addWidget(self.stopButton, 1, 1)

        self.timeDisplay = QLCDNumber(self.gridLayoutWidget)
        self.timeDisplay.setStyleSheet('background-color: transparent')
        self.timeDisplay.setSegmentStyle(QLCDNumber.Flat)
        self.timeDisplay.setDigitCount(8)
        self.timeDisplay.display(strtime(cue.media.duration))
        self.gridLayout.addWidget(self.timeDisplay, 1, 2)

        self.seekSlider = QClickSlider(self.gridLayoutWidget)
        self.seekSlider.setOrientation(Qt.Horizontal)
        self.seekSlider.setRange(0, cue.media.duration)
        self.seekSlider.setFocusPolicy(Qt.NoFocus)
        self.seekSlider.sliderMoved.connect(self._seek)
        self.seekSlider.sliderJumped.connect(self._seek)
        self.seekSlider.setVisible(False)

        self.dbmeter = QDbMeter(self.gridLayoutWidget)
        self.dbmeter.setVisible(False)

        self.gridLayout.setRowStretch(0, 1)
        self.gridLayout.setRowStretch(1, 2)
        self.gridLayout.setColumnStretch(0, 3)
        self.gridLayout.setColumnStretch(1, 3)
        self.gridLayout.setColumnStretch(2, 5)

        cue.changed('name').connect(self.name_changed)
        cue.media.changed('duration').connect(self.update_duration)
        cue.media.played.connect(self._pause_to_play)
        cue.media.paused.connect(self._play_to_pause)

        self.fade = self.cue.media.element('Fade')
        if self.fade is not None:
            self.fade.enter_fadein.connect(self.enter_fadein)
            self.fade.enter_fadeout.connect(self.enter_fadeout)
            self.fade.exit_fadein.connect(self.exit_fade)
            self.fade.exit_fadeout.connect(self.exit_fade)

    def enter_fadeout(self):
        p = self.timeDisplay.palette()
        p.setColor(p.Text, QColor(255, 50, 50))
        self.timeDisplay.setPalette(p)

    def enter_fadein(self):
        p = self.timeDisplay.palette()
        p.setColor(p.Text, QColor(0, 255, 0))
        self.timeDisplay.setPalette(p)

    def exit_fade(self):
        self.timeDisplay.setPalette(self.palette())

    def name_changed(self, name):
        self.nameLabel.setText(name)
        self.nameLabel.setToolTip(name)

    def set_accurate_time(self, enable):
        self._accurate_time = enable

    def set_seek_visible(self, visible):
        if visible and not self.seekSlider.isVisible():
            self.gridLayout.addWidget(self.seekSlider, 2, 0, 1, 3)
            self.gridLayout.setRowStretch(2, 1)
        elif not visible and self.seekSlider.isVisible():
            self.gridLayout.removeWidget(self.seekSlider)
            self.gridLayout.setRowStretch(2, 0)

        self.seekSlider.setVisible(visible)

    def set_dbmeter_visible(self, visible):
        if self._dbmeter_element is not None:
            self._dbmeter_element.level_ready.disconnect(self.dbmeter.plot)
            self._dbmeter_element = None

        if visible:
            self._dbmeter_element = self.cue.media.element('DbMeter')
            if self._dbmeter_element is not None:
                self._dbmeter_element.level_ready.connect(self.dbmeter.plot)

        # Add/Remove the QDbMeter in the layout
        if visible and not self.dbmeter.isVisible():
            self.gridLayout.addWidget(self.dbmeter, 0, 3, 4, 1)
            self.gridLayout.setColumnStretch(3, 1)
        elif not visible and self.dbmeter.isVisible():
            self.gridLayout.removeWidget(self.dbmeter)
            self.gridLayout.setColumnStretch(3, 0)

        self.dbmeter.setVisible(visible)

    def _time_updated(self, time):
        if not self.visibleRegion().isEmpty():
            # If the given value is the duration or < 0 set the time to 0
            if time == self.cue.media.duration or time < 0:
                time = 0

            # Set the value the seek slider
            self.seekSlider.setValue(time)

            # Show the time in the widget
            self.timeDisplay.display(strtime(self.cue.media.duration - time,
                                             accurate=self._accurate_time))

    def update_duration(self, media, duration):
        self.seekSlider.setMaximum(duration)

    def _stop(self, *args):
        self.cue.stop()

    def _play(self, *args):
        self.cue.start()

    def _pause(self, *args):
        self.cue.pause()

    def _seek(self, position):
        self.cue.media.seek(position)

    def _play_to_pause(self):
        self.playPauseButton.clicked.disconnect()
        self.playPauseButton.clicked.connect(self._play)
        self.playPauseButton.setIcon(QIcon.fromTheme('media-playback-start'))

    def _pause_to_play(self):
        self.playPauseButton.clicked.disconnect()
        self.playPauseButton.clicked.connect(self._pause)
        self.playPauseButton.setIcon(QIcon.fromTheme('media-playback-pause'))
示例#33
0
class MainWindow(QMainWindow):


	def __init__(self):

		super().__init__()

		self.left = 10
		self.top = 10
		self.title = 'Rodent Vitals Monitoring Software Demo'
		self.width = 700
		self.height = 500
		self.model = [] 

		#Matplotlib graphs 


		self.lbl = PlotCanvas()

		#LCDs for numerical vital monitoring 

		self.lcd_BR = QLCDNumber(self)
		self.lcd_HR = QLCDNumber(self)
		self.lcd_TEMP = QLCDNumber(self)


		self.control = PID()
		self.control.setPoint(set_point=37)

		print("Initializing MainWindow")


		self.initUI()

	def initUI(self):  

		# Set Main Window Geometry and Title

		self.setGeometry(self.left, self.top, self.width, self.height)
		self.setWindowTitle(self.title)  

		#LCDs for numerical vital monitoring 

		
		self.lcd_BR.setSegmentStyle(QLCDNumber.Flat)
		paletteBR = self.lcd_BR.palette()
		paletteBR.setColor(paletteBR.WindowText, QtGui.QColor(85, 85, 240))
		self.lcd_BR.setPalette(paletteBR)
		self.lcd_BR.display(58)

		
		self.lcd_HR.setSegmentStyle(QLCDNumber.Flat)
		paletteHR = self.lcd_HR.palette()
		paletteHR.setColor(paletteHR.WindowText, QtGui.QColor(85, 255, 85))
		self.lcd_HR.setPalette(paletteHR)
		self.lcd_HR.display(287)

		
		self.lcd_TEMP.setSegmentStyle(QLCDNumber.Flat)
		paletteTEMP = self.lcd_TEMP.palette()
		paletteTEMP.setColor(paletteTEMP.WindowText, QtGui.QColor(255, 85, 85))
		self.lcd_TEMP.setPalette(paletteTEMP)
		self.lcd_TEMP.display(17)



		#Labels for vitals 


		BRlabel = QLabel('Breathing Rate (breaths/min)')
		HRlabel = QLabel('Heart Rate (beats/min)')
		TEMPlabel = QLabel('Subject Temperature (Celsius)')


		#Setting up Frame Layout 

		wid = QWidget(self)
		self.setCentralWidget(wid)

		box = QHBoxLayout(self)


		#Boxes for LCD vitals 

		box_HRLCD = QHBoxLayout(self)
		box_BRLCD = QHBoxLayout(self)
		box_TEMPLCD = QHBoxLayout(self)

		box_HRLCD.addWidget(self.lcd_HR)
		box_BRLCD.addWidget(self.lcd_BR)
		box_TEMPLCD.addWidget(self.lcd_TEMP)


		box_graph = QHBoxLayout(self)

		box_graph.addWidget(self.lbl)


		left = QFrame(self)
		left.setFrameShape(QFrame.Box)



		topright = QFrame(self)
		topright.setFrameShape(QFrame.Box)

		middleright = QFrame(self)
		middleright.setFrameShape(QFrame.Box)

		bottomright = QFrame(self)
		bottomright.setFrameShape(QFrame.Box)

		left.setLayout(box_graph)
		topright.setLayout(box_HRLCD)

		middleright.setLayout(box_BRLCD)


		bottomright.setLayout(box_TEMPLCD)


		# Splitting frames and adding layout to window 


		splitter1 = QSplitter(Qt.Vertical)
		splitter1.addWidget(topright)
		splitter1.addWidget(middleright)

		splitter2 = QSplitter(Qt.Vertical)
		splitter2.addWidget(splitter1)
		splitter2.addWidget(bottomright)

		splitter3 = QSplitter(Qt.Horizontal)
		splitter3.addWidget(left)
		splitter3.addWidget(splitter2)


		box.addWidget(splitter3)
		wid.setLayout(box)   


	
		menubar = self.menuBar()
		fileMenu = menubar.addMenu('File')
		viewMenu = menubar.addMenu('View')
		recordingMenu = menubar.addMenu('Recording Options')

		self.statusbar = self.statusBar()
		self.statusbar.showMessage('Ready')
	
		impMenu = QMenu('Import', self)
		impAct = QAction('Import data', self) 
		impAct.triggered.connect(lambda: self.loadCsv)
		impMenu.addAction(impAct)

		expMenu = QMenu('Export', self)
		expAct = QAction('Export data', self) 
		expAct.triggered.connect(lambda: self.writeCsv)
		expMenu.addAction(expAct)
		
		newAct = QAction('New', self)       

		changeWindowSize = QAction('Change Window Size', self)
		changeWindowSize.triggered.connect(lambda: self.windowSizeInput()) 

		resetWindow = QAction('Reset Window to Present', self)
		resetWindow.triggered.connect(lambda: self.windowReset())


		recordingMenu.addAction(changeWindowSize)

		recordingMenu.addAction(resetWindow)

		
		fileMenu.addAction(newAct)
		fileMenu.addMenu(impMenu)
		fileMenu.addMenu(expMenu)
		fileMenu.addMenu(recordingMenu)

		#Making the status bar 

		viewStatAct = QAction('View statusbar', self, checkable=True)
		viewStatAct.setStatusTip('View statusbar')
		viewStatAct.setChecked(True)
		viewStatAct.triggered.connect(self.toggleMenu)
		viewMenu.addAction(viewStatAct)

		#Making the toolbar 

		exitAct = QAction(QIcon('cancel-512.png'), 'Exit', self)
		exitAct.triggered.connect(lambda: sys.exit())

		exportAct = QAction(QIcon('512x512.png'), 'Export Vitals', self)
		exportAct.triggered.connect(lambda: self.writeRealCsv())

		exportRawAct = QAction(QIcon('document.png'), 'Export Raw Data', self)
		exportRawAct.triggered.connect(lambda: self.writeVoltageCsv())

		startAct = QAction(QIcon('graphs icon.png'), 'Start Graphs', self)
		startAct.triggered.connect(lambda: self.lbl.plot(lcd_HR=self.lcd_HR, lcd_BR=self.lcd_BR, lcd_TEMP=self.lcd_TEMP))

		heatAct = QAction(QIcon('temperature icon.png'), 'Start Temperature', self)
		heatAct.triggered.connect(lambda: self.tempControl())

		vitalsAct = QAction(QIcon('vitals icon.png'), 'Start Vitals', self)
		vitalsAct.triggered.connect(lambda: self.displayVitals())



		
		self.toolbar = self.addToolBar('Exit')
		self.toolbar = self.addToolBar('Save')
		self.toolbar = self.addToolBar('Export')
		self.toolbar = self.addToolBar('Export')

		self.toolbar.addAction(exitAct)
		self.toolbar.addAction(startAct)
		self.toolbar.addAction(heatAct)
		self.toolbar.addAction(exportRawAct)
		self.toolbar.addAction(exportAct)

		print("Creating toolbar menus and displaying window")
		#Setting window size and showing
  
		self.show()

	def Close(self):

		self.p.stop()
		GPIO.cleanup()
		sys.exit()


	def tempControl(self):


		while True:

			current_value = ConvertTemp(ReadChannel(2), 1)

			#print(ReadChannel(2))
			print(current_value)

			newvalue = self.control.update(current_value=current_value)
			print(newvalue)

			if newvalue > current_value:

				direction = 1


			else: 

				direction = 0


			GPIO.output(33, 1)
			GPIO.output(29, direction)
			
			time.sleep(2)

		
	def startVitals(self):

		self.tempControl()
		self.lbl.plot()
		

	def windowSizeInput(self):

		# open a smaller window with a numerical input option 

		num,ok = QInputDialog.getInt(self,"Window Dialog","enter a number")
		
		if ok:
			newSize = num
			self.lbl.plot(window=newSize, start = self.lbl.current_time)

	def windowReset(self):

		self.lbl.plot(window = self.lbl.window, start = self.lbl.current_time)
	
	def toggleMenu(self, state):
		
		if state:
			self.statusbar.show()
		else:
			self.statusbar.hide()

	# IN PROGRESS - last line of loadCSV needs to be changed and graphs need to be made self variables upon initialization for dynamic changing and one for models for each vital

	def writeVoltageCsv(self, fileName):

		cwd = os.getcwd()

		volt_hr = self.lbl.volt_hr
		volt_br = self.lbl.volt_br
		volt_temp = self.lbl.volt_temp

		fileName_volt = cwd + fileName + "Voltage_Data.csv"
		

		data = pd.DataFrame({'Heart Rate (V)':volt_hr, 'Breathing Rate (V)':volt_br, 'Temperature (V)':volt_temp})
		data.to_csv(fileName_volt, index=False)

	def writeRealCsv(self, fileName):

		real_hr = self.lbl.real_hr
		real_br = self.lbl.real_br
		real_temp = self.lbl.real_temp

		fileName_real = cwd + fileName + "Vital_Data.csv"

		data = pd.DataFrame({'Heart Rate (bpm)':real_hr, 'Breathing Rate (bpm)':real_temp, 'Temperature (F)':real_temp})
		data.to_csv(fileName_real, index=False)
class Objetives(QWidget):
    NumButtons = 3

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

        self.createDisplay()
        self.createDisplayAverage()
        self.createButtons()

        self.numVictory = 0
        self.numLosses = 0

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.displayLCD)
        mainLayout.addWidget(self.horizontalGroupBox)
        mainLayout.addWidget(self.displayWinPercent)

        self.setLayout(mainLayout)

        self.setWindowTitle("Objetives")

    def createButtons(self):
        self.horizontalGroupBox = QGroupBox("")
        layout = QGridLayout()

        self.victoryButton = self.createButton("Victory", "+",self.addVictoryOrLosses)
        self.lossesButton = self.createButton("Losses", "+",self.addVictoryOrLosses)
        self.victoryDecreaseButton = self.createButton("DV","-",self.addVictoryOrLosses)
        self.losseDecreaseButton = self.createButton("DL","-",self.addVictoryOrLosses)

        self.lossesButton.setMinimumWidth(150)
        self.victoryButton.setMinimumWidth(150)

        self.losseDecreaseButton.setMaximumHeight(20)
        self.victoryDecreaseButton.setMaximumHeight(20)

        layout.addWidget(self.victoryButton, 0, 0, 1, 1)
        layout.addWidget(self.lossesButton, 0, 2, 1, 1)
        layout.addWidget(self.victoryDecreaseButton, 1, 0, 1, 1)
        layout.addWidget(self.losseDecreaseButton, 1, 2, 1, 1)

        self.horizontalGroupBox.setLayout(layout)

    def createDisplayAverage(self):
        self.displayWinPercent = QGroupBox("Wins")
        layout = QHBoxLayout()

        self.progressBar = QProgressBar()
        self.progressBar.setRange(0, 100)
        # self.progressBar.setValue(5000)

        layout.addWidget(self.progressBar)

        self.displayWinPercent.setLayout(layout)

    def createDisplay(self):
        self.displayLCD = QGroupBox("")
        layout = QHBoxLayout()

        paletteLosses = QPalette()
        paletteVictory = QPalette()

        paletteLosses.setColor(paletteLosses.WindowText, QColor(255, 000, 000))
        paletteVictory.setColor(paletteVictory.WindowText, QColor(000, 255, 000))

        self.lossesLcd = QLCDNumber(3)
        self.lossesLcd.setSegmentStyle(QLCDNumber.Filled)
        self.lossesLcd.setPalette(paletteLosses)

        self.victoryLcd = QLCDNumber(3)
        self.victoryLcd.setSegmentStyle(QLCDNumber.Filled)
        self.victoryLcd.setPalette(paletteVictory)

        self.lossesLcd.setMinimumHeight(100)
        self.victoryLcd.setMinimumHeight(100)

        self.lossesLcd.setMinimumWidth(150)
        self.victoryLcd.setMinimumWidth(150)

        layout.addWidget(self.victoryLcd)
        layout.addWidget(self.lossesLcd)

        self.displayLCD.setLayout(layout)

    def addVictoryOrLosses(self):
        clickedButton = self.sender()
        clickedOperator = clickedButton.text()
        operand = float(1)

        if clickedOperator == "Victory":
            self.numVictory = self.numVictory + 1
            self.victoryLcd.display(str(self.numVictory))

        if clickedOperator == "DV":
            self.numVictory = self.numVictory - 1
            self.victoryLcd.display(str(self.numVictory))

        if clickedOperator == "Losses":
            self.numLosses = self.numLosses + 1
            self.lossesLcd.display(str(self.numLosses))

        if clickedOperator == "DL":
            self.numLosses = self.numLosses - 1
            self.lossesLcd.display(str(self.numLosses))

        self.calculateAverage()

    def calculateAverage(self):
        total = self.numVictory + self.numLosses

        # self.progressBar.setValue((int(self.numVictory / total * 100)))
        self.progressBar.setValue(100)
        # self.victoryLcdAv.display(str(int(self.numVictory / total * 100)))
        # self.lossesLcdAv.display(str(int(self.numLosses / total * 100)))

    def createButton(self, text, op, member):
        button = Button(text,op)
        button.clicked.connect(member)
        return button
示例#35
0
class PomodoroTimer(QWidget):
    def __init__(self):  # Create default constructor
        super().__init__()
        self.initializeUI()

    def initializeUI(self):
        """Initialize the window and display its contents to the screen."""
        self.setMinimumSize(500, 400)
        self.setWindowTitle("1.1 - Pomodoro Timer")
        self.setWindowIcon(QIcon("images/tomato.png"))

        self.pomodoro_limit = POMODORO_TIME
        self.short_break_limit = SHORT_BREAK_TIME
        self.long_break_limit = LONG_BREAK_TIME

        self.setupTabsAndWidgets()

        # Variables related to the current tabs and widgets displayed in the GUI’s window
        self.current_tab_selected = 0
        self.current_start_button = self.pomodoro_start_button
        self.current_stop_button = self.pomodoro_stop_button
        self.current_reset_button = self.pomodoro_reset_button
        self.current_time_limit = self.pomodoro_limit
        self.current_lcd = self.pomodoro_lcd

        # Variables related to user's current task
        self.task_is_set = False
        self.number_of_tasks = 0
        self.task_complete_counter = 0

        # Create timer object
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateTimer)

        self.show()

    def setupTabsAndWidgets(self):
        """Set up the tab bar for the different pomodoro stages: pomodoro, 
        short break, long break."""
        # Create the tab bar and the QWidgets (containers) for each tab
        self.tab_bar = QTabWidget(self)

        self.pomodoro_tab = QWidget()
        self.pomodoro_tab.setObjectName("Pomodoro")
        self.short_break_tab = QWidget()
        self.short_break_tab.setObjectName("ShortBreak")
        self.long_break_tab = QWidget()
        self.long_break_tab.setObjectName("LongBreak")

        self.tab_bar.addTab(self.pomodoro_tab, "Pomodoro")
        self.tab_bar.addTab(self.short_break_tab, "Short Break")
        self.tab_bar.addTab(self.long_break_tab, "Long Break")

        self.tab_bar.currentChanged.connect(self.tabsSwitched)

        # Call the functions that contain the widgets for each tab
        self.pomodoroTab()
        self.shortBreakTab()
        self.longBreakTab()

        # Create the line edit and button widgets and layout for Pomodoro Taskbar
        self.enter_task_lineedit = QLineEdit()
        self.enter_task_lineedit.setClearButtonEnabled(True)
        self.enter_task_lineedit.setPlaceholderText("Enter Your Current Task")

        confirm_task_button = QPushButton(QIcon("images/plus.png"), None)
        confirm_task_button.setObjectName("ConfirmButton")
        confirm_task_button.clicked.connect(self.addTaskToTaskbar)

        task_entry_h_box = QHBoxLayout()
        task_entry_h_box.addWidget(self.enter_task_lineedit)
        task_entry_h_box.addWidget(confirm_task_button)

        self.tasks_v_box = QVBoxLayout()

        task_v_box = QVBoxLayout()
        task_v_box.addLayout(task_entry_h_box)
        task_v_box.addLayout(self.tasks_v_box)

        # Container for taskbar
        task_bar_gb = QGroupBox("Tasks")
        task_bar_gb.setLayout(task_v_box)

        # Create and set layout for the main window
        main_v_box = QVBoxLayout()
        main_v_box.addWidget(self.tab_bar)
        main_v_box.addWidget(task_bar_gb)
        self.setLayout(main_v_box)

    def pomodoroTab(self):
        """Set up the Pomodoro tab, widgets and layout."""
        # Convert starting time to display on timer
        start_time = self.calculateDisplayTime(self.pomodoro_limit)

        self.pomodoro_lcd = QLCDNumber()
        self.pomodoro_lcd.setObjectName("PomodoroLCD")
        self.pomodoro_lcd.setSegmentStyle(QLCDNumber.Filled)
        self.pomodoro_lcd.display(start_time)

        self.pomodoro_start_button = QPushButton("Start")
        self.pomodoro_start_button.clicked.connect(self.startCountDown)

        self.pomodoro_stop_button = QPushButton("Stop")
        self.pomodoro_stop_button.clicked.connect(self.stopCountDown)

        self.pomodoro_reset_button = QPushButton("Reset")
        self.pomodoro_reset_button.clicked.connect(self.resetCountDown)

        button_h_box = QHBoxLayout()  # Horizontal layout for buttons
        button_h_box.addWidget(self.pomodoro_start_button)
        button_h_box.addWidget(self.pomodoro_stop_button)
        button_h_box.addWidget(self.pomodoro_reset_button)

        # Create and set layout for the pomodoro tab
        v_box = QVBoxLayout()
        v_box.addWidget(self.pomodoro_lcd)
        v_box.addLayout(button_h_box)
        self.pomodoro_tab.setLayout(v_box)

    def shortBreakTab(self):
        """Set up the short break tab, widgets and layout."""
        # Convert starting time to display on timer
        start_time = self.calculateDisplayTime(self.short_break_limit)

        self.short_break_lcd = QLCDNumber()
        self.short_break_lcd.setObjectName("ShortLCD")
        self.short_break_lcd.setSegmentStyle(QLCDNumber.Filled)
        self.short_break_lcd.display(start_time)

        self.short_start_button = QPushButton("Start")
        self.short_start_button.clicked.connect(self.startCountDown)

        self.short_stop_button = QPushButton("Stop")
        self.short_stop_button.clicked.connect(self.stopCountDown)

        self.short_reset_button = QPushButton("Reset")
        self.short_reset_button.clicked.connect(self.resetCountDown)

        button_h_box = QHBoxLayout()  # Horizontal layout for buttons
        button_h_box.addWidget(self.short_start_button)
        button_h_box.addWidget(self.short_stop_button)
        button_h_box.addWidget(self.short_reset_button)

        # Create and set layout for the short break tab
        v_box = QVBoxLayout()
        v_box.addWidget(self.short_break_lcd)
        v_box.addLayout(button_h_box)
        self.short_break_tab.setLayout(v_box)

    def longBreakTab(self):
        """Set up the long break tab, widgets and layout."""
        # Convert starting time to display on timer
        start_time = self.calculateDisplayTime(self.long_break_limit)

        self.long_break_lcd = QLCDNumber()
        self.long_break_lcd.setObjectName("LongLCD")
        self.long_break_lcd.setSegmentStyle(QLCDNumber.Filled)
        self.long_break_lcd.display(start_time)

        self.long_start_button = QPushButton("Start")
        self.long_start_button.clicked.connect(self.startCountDown)

        self.long_stop_button = QPushButton("Stop")
        self.long_stop_button.clicked.connect(self.stopCountDown)

        self.long_reset_button = QPushButton("Reset")
        self.long_reset_button.clicked.connect(self.resetCountDown)

        button_h_box = QHBoxLayout()  # Horizontal layout for buttons
        button_h_box.addWidget(self.long_start_button)
        button_h_box.addWidget(self.long_stop_button)
        button_h_box.addWidget(self.long_reset_button)

        # Create and set layout for the long break tab
        v_box = QVBoxLayout()
        v_box.addWidget(self.long_break_lcd)
        v_box.addLayout(button_h_box)
        self.long_break_tab.setLayout(v_box)

    def startCountDown(self):
        """Starts the timer. If the current tab's time is 00:00, reset the time 
        if user pushes the start button."""
        self.current_start_button.setEnabled(False)

        # Used to reset counter_label if user has already has completed four pomodoro cycles
        if self.task_is_set == True and self.task_complete_counter == 0:
            self.counter_label.setText("{}/4".format(
                self.task_complete_counter))

        remaining_time = self.calculateDisplayTime(self.current_time_limit)
        if remaining_time == "00:00":
            self.resetCountDown()
            self.timer.start(1000)
        else:
            self.timer.start(1000)

    def stopCountDown(self):
        """If the timer is already running, then stop the timer."""
        if self.timer.isActive() != False:
            self.timer.stop()
            self.current_start_button.setEnabled(True)

    def resetCountDown(self):
        """Resets the time for the current tab when the reset button is selected."""
        self.stopCountDown()  # Stop countdown if timer is running

        # Reset time for currently selected tab
        if self.current_tab_selected == 0:  # Pomodoro tab
            self.pomodoro_limit = POMODORO_TIME
            self.current_time_limit = self.pomodoro_limit
            reset_time = self.calculateDisplayTime(self.current_time_limit)

        elif self.current_tab_selected == 1:  # Short break tab
            self.short_break_limit = SHORT_BREAK_TIME
            self.current_time_limit = self.short_break_limit
            reset_time = self.calculateDisplayTime(self.current_time_limit)

        elif self.current_tab_selected == 2:  # Long break tab
            self.long_break_limit = LONG_BREAK_TIME
            self.current_time_limit = self.long_break_limit
            reset_time = self.calculateDisplayTime(self.current_time_limit)

        self.current_lcd.display(reset_time)

    def updateTimer(self):
        """Updates the timer and the current QLCDNumber widget. Also, update the 
        task counter if a task is set."""
        remaining_time = self.calculateDisplayTime(self.current_time_limit)

        if remaining_time == "00:00":
            self.stopCountDown()
            self.current_lcd.display(remaining_time)

            if self.current_tab_selected == 0 and self.task_is_set == True:
                self.task_complete_counter += 1
                if self.task_complete_counter == 4:
                    self.counter_label.setText(
                        "Time for a long break. {}/4".format(
                            self.task_complete_counter))
                    self.task_complete_counter = 0
                elif self.task_complete_counter < 4:
                    self.counter_label.setText("{}/4".format(
                        self.task_complete_counter))
        else:
            # Update the current timer by decreasing the current running time by one second
            self.current_time_limit -= 1000
            self.current_lcd.display(remaining_time)

    def tabsSwitched(self, index):
        """Depending upon which tab the user is currently looking at, the information
        for that tab needs to be updated. This function updates the different variables
        that keep track of the timer, buttons, lcds and other widgets, and updates them accordingly."""
        self.current_tab_selected = index
        self.stopCountDown()

        # Reset variables, time and widgets depending upon which tab is the current_tab_selected
        if self.current_tab_selected == 0:  # Pomodoro tab
            self.current_start_button = self.pomodoro_start_button
            self.current_stop_button = self.pomodoro_stop_button
            self.current_reset_button = self.pomodoro_reset_button
            self.pomodoro_limit = POMODORO_TIME
            self.current_time_limit = self.pomodoro_limit

            reset_time = self.calculateDisplayTime(self.current_time_limit)
            self.current_lcd = self.pomodoro_lcd
            self.current_lcd.display(reset_time)

        elif self.current_tab_selected == 1:  # Short break tab
            self.current_start_button = self.short_start_button
            self.current_stop_button = self.short_stop_button
            self.current_reset_button = self.short_reset_button
            self.short_break_limit = SHORT_BREAK_TIME
            self.current_time_limit = self.short_break_limit

            reset_time = self.calculateDisplayTime(self.current_time_limit)
            self.current_lcd = self.short_break_lcd
            self.current_lcd.display(reset_time)

        elif self.current_tab_selected == 2:  # Long break tab
            self.current_start_button = self.long_start_button
            self.current_stop_button = self.long_stop_button
            self.current_reset_button = self.long_reset_button
            self.long_break_limit = LONG_BREAK_TIME
            self.current_time_limit = self.long_break_limit

            reset_time = self.calculateDisplayTime(self.current_time_limit)
            self.current_lcd = self.long_break_lcd
            self.current_lcd.display(reset_time)

    def addTaskToTaskbar(self):
        """When the user clicks plus button, the widgets for the new task will be 
        added to the task bar. Only one task is allowed to be entered at a time."""
        text = self.enter_task_lineedit.text()
        self.enter_task_lineedit.clear()

        # Change number_of_tasks if you want to add more tasks to the task bar
        if text != "" and self.number_of_tasks != 1:
            self.enter_task_lineedit.setReadOnly(True)
            self.task_is_set = True
            self.new_task = QLabel(text)

            self.counter_label = QLabel("{}/4".format(
                self.task_complete_counter))
            self.counter_label.setAlignment(Qt.AlignRight)

            self.cancel_task_button = QPushButton(QIcon("images/minus.png"),
                                                  None)
            self.cancel_task_button.setMaximumWidth(24)
            self.cancel_task_button.clicked.connect(self.clearCurrentTask)

            self.new_task_h_box = QHBoxLayout()
            self.new_task_h_box.addWidget(self.new_task)
            self.new_task_h_box.addWidget(self.counter_label)
            self.new_task_h_box.addWidget(self.cancel_task_button)

            self.tasks_v_box.addLayout(self.new_task_h_box)
            self.number_of_tasks += 1

    def clearCurrentTask(self):
        """Delete the current task, and reset variables and widgets related to tasks."""
        # Remove items from parent widget by setting the argument value in
        # setParent() to None
        self.new_task.setParent(None)
        self.counter_label.setParent(None)
        self.cancel_task_button.setParent(None)

        self.number_of_tasks -= 1
        self.task_is_set = False
        self.task_complete_counter = 0

        self.enter_task_lineedit.setReadOnly(False)

    def convertTotalTime(self, time_in_milli):
        """Convert time to milliseconds."""
        minutes = (time_in_milli / (1000 * 60)) % 60
        seconds = (time_in_milli / 1000) % 60
        return int(minutes), int(seconds)

    def calculateDisplayTime(self, time):
        """Calculate the time that should be displayed in the QLCDNumber widget."""
        minutes, seconds = self.convertTotalTime(time)
        amount_of_time = "{:02d}:{:02d}".format(minutes, seconds)
        return amount_of_time
示例#36
0
class App(QWidget):
    """Display window for the main game and start the timer.

    Display options to:
        1. Select letters on the table
        2. Pause/Resume the game
        3. Quit the game

    Attributes:
        wordBank: A string of the words to find in the word search.
        wordBankSplit: A list of strings of words to find in the word search.
        wordSelected: A string to hold the current word selected.
        xVisited: A list of integers to hold the current row values of the letters selected.
        yVisited: A list of integers to hold the current column values of the letters selected.
        inRow: An integer to determine if the letters selected are in consecutive fashion.
        progressValue: An integer to keep track of the words found.
        wordsCompleted: A list of strings of the words found.
        timeFlag: A time flag to keep track of the timer if the game has been paused or resumed.
    """
    def __init__(self):
        """Initiate initUI."""
        super().__init__()
        self.wordBank = ""
        self.wordBankSplit = []
        self.wordSelected = ""
        self.xVisited = []
        self.yVisited = []
        self.inRow = 0
        self.progressValue = 0
        self.wordsCompleted = []
        self.timeFlag = 2
        self.initUI()

    def initUI(self):
        """Initiate UI elements."""
        title = 'Word Search Mania'
        self.setWindowTitle(title)

        self.wordBankBox = QTextEdit()
        self.tableWidget = QTableWidget()
        self.progress = QProgressBar()
        self.timer = PyQt5.QtCore.QTimer()

        self.createTable()
        self.createWordBank()
        self.createProgressBar()
        self.createTimer()
        self.mouseTracking()

        wordBankTitle = QLabel()
        wordBankTitle.setText("       Word Bank")
        font = QFont()
        font.setBold(True)
        wordBankTitle.setFont(font)

        buttonClear = QPushButton('Clear', self)
        buttonClear.setToolTip('This clears your word selection.')
        buttonClear.clicked.connect(self.onClickClear)

        buttonQuit = QPushButton('Quit', self)
        buttonQuit.setToolTip(
            'This will buttonQuit your game. You will loose all progress.')
        buttonQuit.clicked.connect(self.onClickQuit)

        self.buttonPause = QPushButton('Pause')
        self.buttonPause.setToolTip('This pauses the game.')
        self.buttonPause.clicked.connect(self.onClickPause)

        vBox = QVBoxLayout()
        vBox.addWidget(wordBankTitle)
        vBox.addWidget(self.wordBankBox)
        vBox.addWidget(buttonClear)
        vBox.addWidget(self.buttonPause)
        vBox.addWidget(buttonQuit)

        self.grid = QGridLayout()
        self.grid.addLayout(vBox, 0, 1)
        self.grid.addWidget(self.tableWidget, 0, 0)
        self.grid.addWidget(self.progress, 1, 0)
        self.grid.addWidget(self.LCD, 1, 1)

        self.setLayout(self.grid)

        self.tableWidget.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)

        self.show()

    def createTable(self):
        """Generate the word search table."""
        generateAll = False

        global wordBoxChecked
        global rowBoxChecked
        global columnBoxChecked
        global diagonalBoxChecked

        if wordBoxChecked:
            f = open('custom_word_bank.txt', "r")
            wordBoxChecked = False
        else:
            f = open('words_alpha.txt', "r")
            generateAll = True

        wordFileContent = f.readlines()
        wordFileContent = [x.strip() for x in wordFileContent]

        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setRowCount(nElements)
        self.tableWidget.setColumnCount(nElements)

        # Populate table with random letters
        for y in range(0, nElements):
            for x in range(0, nElements):
                self.tableWidget.setItem(
                    x, y,
                    QTableWidgetItem(random.choice(string.ascii_uppercase)))
                self.tableWidget.setColumnWidth(x, 20)
                self.tableWidget.setRowHeight(y, 20)

        # Implements words across rows
        def generateRow(self):
            col = 0
            row = 0
            lastColPosition = 0
            wordDuplicate = False
            while row < nElements:
                while col < nElements:
                    col = random.randint(lastColPosition, nElements)
                    word = wordFileContent[random.randint(
                        0,
                        len(wordFileContent) - 1)]
                    while len(word) < 3:
                        word = wordFileContent[random.randint(
                            0,
                            len(wordFileContent) - 1)]
                    for x in self.wordBank.split():
                        if x == word:
                            wordDuplicate = True
                    if not wordDuplicate:
                        if nElements - col > len(word):
                            lastColPosition = len(word) + col
                            self.wordBank += word + "\n"
                            for x in word:
                                self.tableWidget.setItem(
                                    row, col, QTableWidgetItem(x))
                                col += 1
                            col = nElements
                    wordDuplicate = False
                row += 3
                col = 0
                lastColPosition = 0

        # Implements words down each column
        def generateCol(self):
            col = 0
            row = 0
            lastRowPosition = 0
            decide = 0
            wordDuplicate = False
            while col < nElements:
                while row < nElements:
                    row = random.randint(lastRowPosition, nElements)
                    word = wordFileContent[random.randint(
                        0,
                        len(wordFileContent) - 1)]
                    while len(word) < 3:
                        word = wordFileContent[random.randint(
                            0,
                            len(wordFileContent) - 1)]
                    for x in self.wordBank.split():
                        if x == word:
                            wordDuplicate = True
                    if not wordDuplicate:
                        if nElements - row > len(word):
                            for k in range(row, row + len(word)):
                                if self.tableWidget.item(k,
                                                         col).text().islower():
                                    decide += 1
                            if decide == 0:
                                lastRowPosition = len(word) + row
                                self.wordBank += word + "\n"
                                for y in word:
                                    self.tableWidget.setItem(
                                        row, col, QTableWidgetItem(y))
                                    row += 1
                            decide = 0
                    wordDuplicate = False
                col += 3
                row = 0
                lastRowPosition = 0

        # Implements words down each diagonal in forward
        def generateForwardDiag(self):
            col = 0
            row = 0
            wordCount = 0
            decide = 0
            wordDuplicate = False
            while row < nElements:
                while col < nElements:
                    word = wordFileContent[random.randint(
                        0,
                        len(wordFileContent) - 1)]
                    while len(word) < 3:
                        word = wordFileContent[random.randint(
                            0,
                            len(wordFileContent) - 1)]
                    for x in self.wordBank.split():
                        if x == word:
                            wordDuplicate = True
                    if not wordDuplicate:
                        tempRow = row
                        tempCol = col
                        while tempRow < nElements and tempCol < nElements and wordCount < len(
                                word):
                            if self.tableWidget.item(tempRow,
                                                     tempCol).text().islower():
                                decide += 1
                            tempRow += 1
                            tempCol += 1
                            wordCount += 1
                        tempRow = row
                        tempCol = col
                        if decide == 0 and (
                                len(word) + tempCol) < nElements and (
                                    len(word) + tempRow) < nElements:
                            self.wordBank += word + "\n"
                            for y in word:
                                self.tableWidget.setItem(
                                    tempRow, tempCol, QTableWidgetItem(y))
                                tempCol += 1
                                tempRow += 1
                    decide = 0
                    wordCount = 0
                    col += 1
                    wordDuplicate = False
                row += 1
                col = 0

        # Implements words down each diagonal in backward
        def generateBackwardDiag(self):
            col = nElements - 1
            row = 0
            wordCount = 0
            decide = 0
            wordDuplicate = False
            while row < nElements:
                while col >= 0:
                    word = wordFileContent[random.randint(
                        0,
                        len(wordFileContent) - 1)]
                    while len(word) < 3:
                        word = wordFileContent[random.randint(
                            0,
                            len(wordFileContent) - 1)]
                    for x in self.wordBank.split():
                        if x == word:
                            wordDuplicate = True
                    if not wordDuplicate:
                        tempRow = row
                        tempCol = col
                        while tempRow < nElements and tempCol >= 0 and wordCount < len(
                                word):
                            if self.tableWidget.item(tempRow,
                                                     tempCol).text().islower():
                                decide += 1
                            tempRow += 1
                            tempCol -= 1
                            wordCount += 1
                        tempRow = row
                        tempCol = col
                        if decide == 0 and (tempCol - len(word)) > 0 and (
                                len(word) + tempRow) < nElements:
                            self.wordBank += word + "\n"
                            for y in word:
                                self.tableWidget.setItem(
                                    tempRow, tempCol, QTableWidgetItem(y))
                                tempRow += 1
                                tempCol -= 1
                    decide = 0
                    wordCount = 0
                    col -= 1
                    wordDuplicate = False
                row += 1
                col = nElements - 1

        if generateAll:
            generateRow(self)
            generateCol(self)
            generateForwardDiag(self)
            generateBackwardDiag(self)
        else:
            if rowBoxChecked:
                generateRow(self)
                rowBoxChecked = False
            if columnBoxChecked:
                generateCol(self)
                columnBoxChecked = False
            if diagonalBoxChecked:
                generateForwardDiag(self)
                generateBackwardDiag(self)
                diagonalBoxChecked = False

        for y in range(0, nElements):
            for x in range(0, nElements):
                letter = self.tableWidget.item(x, y).text().lower()
                self.tableWidget.setItem(x, y, QTableWidgetItem(letter))
                self.tableWidget.item(x, y).setTextAlignment(
                    PyQt5.QtCore.Qt.AlignCenter)

        self.tableWidget.horizontalHeader().hide()
        self.tableWidget.verticalHeader().hide()
        self.tableWidget.setShowGrid(False)
        self.tableWidget.clicked.connect(self.onClickLetter)

    def createWordBank(self):
        """Generate a word bank of the words to be found."""
        self.wordBankSplit = self.wordBank.split()
        self.wordBankSplit.sort()
        for x in self.wordBankSplit:
            self.wordBankBox.append(x)
        self.wordBankBox.setReadOnly(True)
        self.wordBankBox.setMaximumWidth(120)
        font = QFont()
        font.setFamily('Arial')
        self.wordBankBox.setFont(font)
        self.wordBankBox.moveCursor(QTextCursor.Start)

    def strikeWord(self, word):
        """Strike word with a line if the word is found."""
        newWord = ""
        for x in word:
            newWord += x + '\u0336'
        self.wordBankSplit = [
            newWord if i == word else i for i in self.wordBankSplit
        ]
        self.wordBankBox.setText("")
        for x in self.wordBankSplit:
            self.wordBankBox.append(x)
        self.wordBankBox.show()
        self.wordBankBox.moveCursor(QTextCursor.Start)

    def mouseTracking(self):
        """Track mouse movement of the table."""
        self.currentHover = [0, 0]
        self.tableWidget.setMouseTracking(True)
        self.tableWidget.cellEntered.connect(self.cellHover)

    def cellHover(self, row, column):
        """Highlight letter if mouse is hovering over it."""
        item = self.tableWidget.item(row, column)
        oldItem = self.tableWidget.item(self.currentHover[0],
                                        self.currentHover[1])
        mouseTracker1 = True
        mouseTracker2 = True
        for x in range(len(self.xVisited)):
            if self.xVisited[x] == row and self.yVisited[x] == column:
                mouseTracker1 = False
            if self.currentHover[0] == self.xVisited[x] and self.currentHover[
                    1] == self.yVisited[x]:
                mouseTracker2 = False
        if mouseTracker1:
            if self.currentHover != [row, column]:
                if item.text().islower():
                    item.setBackground(QBrush(QColor('yellow')))
                if oldItem.text().islower() and mouseTracker2:
                    oldItem.setBackground(QBrush(QColor('white')))
        elif mouseTracker2:
            oldItem.setBackground(QBrush(QColor('white')))
        self.currentHover = [row, column]

    def onClickLetter(self):
        """Highlight letters on selection and highlight word green if found on click."""
        self.wordSelected = ""
        wordBankSplitOriginal = self.wordBank.split()
        selectionTracker = True
        selectionCorrectness = 0
        word = ""
        listX = []
        listY = []

        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            if self.tableWidget.item(
                    currentQTableWidgetItem.row(),
                    currentQTableWidgetItem.column()).text().isupper():
                letter = self.tableWidget.item(
                    currentQTableWidgetItem.row(),
                    currentQTableWidgetItem.column()).text().lower()
                self.tableWidget.setItem(currentQTableWidgetItem.row(),
                                         currentQTableWidgetItem.column(),
                                         QTableWidgetItem(letter))
                self.tableWidget.clearSelection()
            else:
                for currentQTableWidgetItem in self.tableWidget.selectedItems(
                ):
                    for x in range(0, len(self.xVisited)):
                        if currentQTableWidgetItem.row() == self.xVisited[x] and currentQTableWidgetItem.column() == \
                                self.yVisited[x]:
                            selectionTracker = False
                    if selectionTracker:
                        letter = self.tableWidget.item(
                            currentQTableWidgetItem.row(),
                            currentQTableWidgetItem.column()).text().upper()
                        self.tableWidget.setItem(
                            currentQTableWidgetItem.row(),
                            currentQTableWidgetItem.column(),
                            QTableWidgetItem(letter))
                for currentQTableWidgetItem in self.tableWidget.selectedItems(
                ):
                    if selectionTracker:
                        self.tableWidget.item(
                            currentQTableWidgetItem.row(),
                            currentQTableWidgetItem.column()).setBackground(
                                QColor(216, 191, 216))
                for currentQTableWidgetItem in self.tableWidget.selectedItems(
                ):
                    if selectionTracker:
                        self.tableWidget.item(
                            currentQTableWidgetItem.row(),
                            currentQTableWidgetItem.column()).setTextAlignment(
                                PyQt5.QtCore.Qt.AlignCenter)
                    self.tableWidget.clearSelection()

        for x in range(0, nElements):
            for y in range(0, nElements):
                if self.tableWidget.item(x, y).text().isupper():
                    self.wordSelected += self.tableWidget.item(x, y).text()
                    listX.append(x)
                    listY.append(y)
        for x in wordBankSplitOriginal:
            if x == self.wordSelected.lower():
                selectionCorrectness += 1
                word = x
        if selectionCorrectness == 1:  # Makes sure the word is in a row
            for i in range(1, len(listY)):
                if listY[i - 1] == listY[i] - 1 and listX[i - 1] == listX[i]:
                    self.inRow += 1
                if self.inRow == len(listY) - 1:
                    selectionCorrectness += 1
                    self.inRow = 0
        if selectionCorrectness == 1:  # Makes sure the word is in a single column
            for i in range(1, len(listY)):
                if listX[i - 1] == listX[i] - 1 and listY[i - 1] == listY[i]:
                    self.inRow += 1
                if self.inRow == len(listY) - 1:
                    selectionCorrectness += 1
                    self.inRow = 0
        if selectionCorrectness == 1:  # Makes sure the word is in a forward diagonal
            for i in range(1, len(listY)):
                if listX[i - 1] == listX[i] - 1 and listY[i -
                                                          1] == listY[i] - 1:
                    self.inRow += 1
                if self.inRow == len(listY) - 1:
                    selectionCorrectness += 1
                    self.inRow = 0
        if selectionCorrectness == 1:  # Makes sure the word is in a backward diagonal
            for i in range(1, len(listY)):
                if listX[i - 1] == listX[i] - 1 and listY[i -
                                                          1] == listY[i] + 1:
                    self.inRow += 1
                if self.inRow == len(listY) - 1:
                    selectionCorrectness += 1
                    self.inRow = 0

        if selectionCorrectness == 2:
            wordIndex = self.wordSelected.find(word)
            self.progressValue += 1
            self.setProgressBar()
            self.strikeWord(word)
            self.wordsCompleted.append(word)
            for i in range(wordIndex, wordIndex + len(word)):
                letterI = self.tableWidget.item(listX[i],
                                                listY[i]).text().lower()
                self.tableWidget.setItem(listX[i], listY[i],
                                         QTableWidgetItem(letterI))
            for i in range(wordIndex, wordIndex + len(word)):
                self.tableWidget.item(listX[i], listY[i]).setBackground(
                    QColor(144, 238, 144))
                self.xVisited.append(listX[i])
                self.yVisited.append(listY[i])
            for i in range(wordIndex, wordIndex + len(word)):
                self.tableWidget.item(listX[i], listY[i]).setTextAlignment(
                    PyQt5.QtCore.Qt.AlignCenter)

    def onClickClear(self):
        """Clear word selection on button click."""
        self.wordSelected = ""
        for x in range(0, nElements):
            for y in range(0, nElements):
                if self.tableWidget.item(x, y).text().isupper():
                    letterI = self.tableWidget.item(x, y).text().lower()
                    self.tableWidget.setItem(x, y, QTableWidgetItem(letterI))
                    self.tableWidget.item(x, y).setTextAlignment(
                        PyQt5.QtCore.Qt.AlignCenter)

    def onClickQuit(self):
        """Display option to quit the app on button click."""
        quitMessage = QMessageBox()
        quitMessage = QMessageBox.question(
            self, "Quit", "Are you sure you would like to buttonQuit?",
            QMessageBox.No | QMessageBox.Yes)
        if quitMessage == QMessageBox.Yes:
            sys.exit()
        else:
            pass

    def createProgressBar(self):
        """Generate progress bar of with the progress of the words found until completion."""
        self.progress.setRange(0, len(self.wordBank.split()))
        self.progress.setToolTip("Shows your word completion progress.")

    def setProgressBar(self):
        """Set value for the progress bar."""
        self.progress.setValue(self.progressValue)

    def createTimer(self):
        """Generate a timer."""
        self.timer.timeout.connect(self.Time)
        self.timer.start(1000)
        self.time = PyQt5.QtCore.QTime(0, 0, 0)

        self.LCD = QLCDNumber()
        self.LCD.display(self.time.toString("hh:mm:ss"))
        self.LCD.setSegmentStyle(QLCDNumber.Flat)

    def Time(self):
        """Increment timer by a second."""
        self.time = self.time.addSecs(1)
        self.LCD.display(self.time.toString("hh:mm:ss"))

        if len(self.wordsCompleted) == len(self.wordBankSplit):
            self.timer.stop()
            self.endTime = self.time.toString("hh:mm:ss")
            self.addHighScore()
            self.close()
            self.openHighscoreMenu = HighScoreMenu()
            self.openHighscoreMenu.show()

    def onClickPause(self):
        """Pause and resume the game on button click."""
        if self.timeFlag % 2 == 0:
            self.timer.stop()
            self.timeFlag += 1
            self.tableWidget.hide()
            self.buttonPause.setText("Unpause")
        else:
            self.timer.start()
            self.timeFlag += 1
            self.tableWidget.show()
            self.tableWidget.clearSelection()
            self.buttonPause.setText("Pause")

    def addHighScore(self):
        """Save highScore to WS_Highscores text file."""
        with open("highscores.txt", "a") as highscoreFile:
            if 10 <= nElements <= 19:
                highscoreFile.write("Easy\n")
            elif 20 <= nElements <= 29:
                highscoreFile.write("Medium\n")
            else:
                highscoreFile.write("Hard\n")
            highscoreFile.write(str(self.endTime) + "\n")
示例#37
0
class Ui_Widget(object):
    """ Klasa definiująca GUI """

    def setupUi(self, Widget):

        # widgety rysujące kształty, instancje klasy Ksztalt
        self.ksztalt1 = Ksztalt(self, Ksztalty.Polygon)
        self.ksztalt2 = Ksztalt(self, Ksztalty.Ellipse)
        self.ksztaltAktywny = self.ksztalt1

        # przyciski CheckBox ###
        uklad = QVBoxLayout()  # układ pionowy
        self.grupaChk = QButtonGroup()
        for i, v in enumerate(('Kwadrat', 'Koło', 'Trójkąt', 'Linia')):
            self.chk = QCheckBox(v)
            self.grupaChk.addButton(self.chk, i)
            uklad.addWidget(self.chk)
        self.grupaChk.buttons()[self.ksztaltAktywny.ksztalt].setChecked(True)
        # CheckBox do wyboru aktywnego kształtu
        self.ksztaltChk = QCheckBox('<=')
        self.ksztaltChk.setChecked(True)
        uklad.addWidget(self.ksztaltChk)

        # układ poziomy dla kształtów oraz przycisków CheckBox
        ukladH1 = QHBoxLayout()
        ukladH1.addWidget(self.ksztalt1)
        ukladH1.addLayout(uklad)
        ukladH1.addWidget(self.ksztalt2)
        # koniec CheckBox ###

        # Slider i LCDNumber ###
        self.suwak = QSlider(Qt.Horizontal)
        self.suwak.setMinimum(0)
        self.suwak.setMaximum(255)
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        # układ poziomy (splitter) dla slajdera i lcd
        ukladH2 = QSplitter(Qt.Horizontal, self)
        ukladH2.addWidget(self.suwak)
        ukladH2.addWidget(self.lcd)
        ukladH2.setSizes((125, 75))

        # przyciski RadioButton ###
        self.ukladR = QHBoxLayout()
        for v in ('R', 'G', 'B'):
            self.radio = QRadioButton(v)
            self.ukladR.addWidget(self.radio)
        self.ukladR.itemAt(0).widget().setChecked(True)
        # grupujemy przyciski
        self.grupaRBtn = QGroupBox('Opcje RGB')
        self.grupaRBtn.setLayout(self.ukladR)
        self.grupaRBtn.setObjectName('Radio')
        self.grupaRBtn.setCheckable(True)
        # układ poziomy dla grupy Radio
        ukladH3 = QHBoxLayout()
        ukladH3.addWidget(self.grupaRBtn)
        # koniec RadioButton ###

        # Lista ComboBox i SpinBox ###
        self.listaRGB = QComboBox(self)
        for v in ('R', 'G', 'B'):
            self.listaRGB.addItem(v)
        self.listaRGB.setEnabled(False)
        # SpinBox
        self.spinRGB = QSpinBox()
        self.spinRGB.setMinimum(0)
        self.spinRGB.setMaximum(255)
        self.spinRGB.setEnabled(False)
        # układ pionowy dla ComboBox i SpinBox
        uklad = QVBoxLayout()
        uklad.addWidget(self.listaRGB)
        uklad.addWidget(self.spinRGB)
        # do układu poziomego grupy Radio dodajemy układ ComboBox i SpinBox
        ukladH3.insertSpacing(1, 25)
        ukladH3.addLayout(uklad)
        # koniec ComboBox i SpinBox ###

        # przyciski PushButton ###
        uklad = QHBoxLayout()
        self.grupaP = QButtonGroup()
        self.grupaP.setExclusive(False)
        for v in ('R', 'G', 'B'):
            self.btn = QPushButton(v)
            self.btn.setCheckable(True)
            self.grupaP.addButton(self.btn)
            uklad.addWidget(self.btn)
        # grupujemy przyciski
        self.grupaPBtn = QGroupBox('Przyciski RGB')
        self.grupaPBtn.setLayout(uklad)
        self.grupaPBtn.setObjectName('Push')
        self.grupaPBtn.setCheckable(True)
        self.grupaPBtn.setChecked(False)
        # koniec PushButton ###

        # główny układ okna, wertykalny ###
        ukladOkna = QVBoxLayout()
        ukladOkna.addLayout(ukladH1)
        ukladOkna.addWidget(ukladH2)
        ukladOkna.addLayout(ukladH3)
        ukladOkna.addWidget(self.grupaPBtn)

        self.setLayout(ukladOkna)  # przypisanie układu do okna głównego
        self.setWindowTitle('Widżety')
示例#38
0
    def __init__(self, parent = None):
        QWidget.__init__(self, parent, Qt.Window)

        self.board = TetrixBoard()
        self.indictor = TetrixIndictor()

        nextPieceLabel = QLabel(self)
        nextPieceLabel.setFrameStyle(QFrame.Box | QFrame.Raised)
        nextPieceLabel.setAlignment(Qt.AlignCenter)
        self.board.setNextPieceLabel(nextPieceLabel)

        scoreLcd = QLCDNumber(6)
        scoreLcd.setSegmentStyle(QLCDNumber.Filled)
        levelLcd = QLCDNumber(2)
        levelLcd.setSegmentStyle(QLCDNumber.Filled)
        linesLcd = QLCDNumber(6)
        linesLcd.setSegmentStyle(QLCDNumber.Filled)

        startButton = QPushButton(self.tr("&Start"))
        startButton.setFocusPolicy(Qt.NoFocus)
        quitButton = QPushButton(self.tr("E&xit"))
        quitButton.setFocusPolicy(Qt.NoFocus)
        pauseButton = QPushButton(self.tr("&Pause"))
        pauseButton.setFocusPolicy(Qt.NoFocus)

        startButton.clicked.connect(self.board.start)
        pauseButton.clicked.connect(self.board.pause)
        quitButton.clicked.connect(self.close)
        self.board.scoreChanged.connect(scoreLcd.display)
        self.board.levelChanged.connect(levelLcd.display)
        self.board.linesRemovedChanged.connect(linesLcd.display)
        self.board.act.connect(self.indictor.showIndictor)

        layout1 = QHBoxLayout()
        layout3 = QVBoxLayout()
        layout3.addWidget(self.board)
        layout3.addWidget(self.indictor)
        layout3.setSpacing(0)
        layout1.addLayout(layout3)
        layout2 = QVBoxLayout()
        layout2.addWidget(self.createLabel(self.tr("Next Block")))
        layout2.addWidget(nextPieceLabel)
        layout2.addWidget(self.createLabel(self.tr("Level")))
        layout2.addWidget(levelLcd)
        layout2.addWidget(self.createLabel(self.tr("Score")),)
        layout2.addWidget(scoreLcd)
        layout2.addWidget(self.createLabel(self.tr("Total Lines")))
        layout2.addWidget(linesLcd)
        layout2.addWidget(startButton)
        layout2.addWidget(quitButton)
        layout2.addWidget(pauseButton)
        layout1.addLayout(layout2)
        layout1.setStretch(0, 75)
        layout1.setStretch(1, 25)
        self.setLayout(layout1)

        self.setWindowTitle(self.tr("Tetrix"))
        self.resize(self.logicalDpiX() / 96 * 275, self.logicalDpiY() / 96 * 380)

        r = self.geometry()
        r.moveCenter(QApplication.instance().desktop().screenGeometry().center())
        self.setGeometry(r)
示例#39
0
文件: phase10.py 项目: trawl/gamelog
class Phase10PlayerWidget(GamePlayerWidget):

    roundWinnerSet = QtCore.pyqtSignal(str)

    def __init__(self, nick, engine, bgroup=None, parent=None):
        self.engine = engine
        self.current_phase = min(
            self.engine.getRemainingPhasesFromPlayer(nick))
        self.phases_in_order = self.engine.getPhasesInOrderFlag()
        self.bgroup = bgroup
        super(Phase10PlayerWidget, self).__init__(
            nick, PlayerColours[self.engine.getListPlayers().index(nick)],
            parent)

    def initUI(self):
        css = ("QGroupBox {{ font-size: 28px;"
               "font-weight: bold; color:rgb({},{},{});}}")
        self.setStyleSheet(css.format(self.pcolour.red(),
                                      self.pcolour.green(),
                                      self.pcolour.blue()))
        self.setTitle(self.player)
        super(Phase10PlayerWidget, self).initUI()

        trashWidget = QWidget()
        trashWidget.setLayout(self.mainLayout)

        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addStretch()
        self.upperLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.upperLayout)
        self.upperLayout.addStretch()
        self.phaseNameLabel = QLabel(self)
        self.phaseNameLabel.setStyleSheet(
            "font-weight: bold; font-size: 24px;")
        self.updatePhaseName()
        self.upperLayout.addWidget(self.phaseNameLabel)
        self.upperLayout.addStretch()
        self.lowerLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.lowerLayout)
        self.mainLayout.addStretch()

        self.phaseLabelsLayout = QGridLayout()
        self.phaseLabelsLayout.setSpacing(5)

        self.checkboxLayout = QVBoxLayout()

        self.scoreLCD = QLCDNumber(self)
        self.scoreLCD.setSegmentStyle(QLCDNumber.Flat)
        self.mainLayout.addWidget(self.scoreLCD)
        self.scoreLCD.setNumDigits(3)
        self.scoreLCD.setMinimumWidth(100)
        css = "QLCDNumber {{ color:rgb({},{},{});}}"
        self.scoreLCD.setStyleSheet(css.format(self.pcolour.red(),
                                               self.pcolour.green(),
                                               self.pcolour.blue()))

        # Left part - score
        self.lowerLayout.addWidget(self.iconlabel)
        self.lowerLayout.addWidget(self.scoreLCD)
        self.lowerLayout.addLayout(self.phaseLabelsLayout)
        self.lowerLayout.addLayout(self.checkboxLayout)

        self.iconlabel.setMinimumSize(60, 60)

#         self.scoreLCD.setMinimumWidth(100)
#         self.scoreLCD.setMaximumWidth(200)
#         self.scoreLCD.setMinimumHeight(60)
#         self.scoreLCD.setMaximumHeight(80)

        self.scoreLCD.display(self.engine.getScoreFromPlayer(self.player))

        # Middle part - Phase list
        self.phaseLabels = list()
        for phase in range(1, 11):
            label = Phase10Label(phase, self)
            if phase == self.current_phase:
                label.setCurrent()
            elif self.engine.hasPhaseCompleted(self.player, phase):
                label.setPassed()
            self.phaseLabels.append(label)
            self.phaseLabelsLayout.addWidget(
                label, (phase-1)/5, (phase-1) % 5, 1, 1)

        # Middle part - Inputs
        self.roundWinnerRadioButton = QRadioButton()
        self.bgroup.addButton(self.roundWinnerRadioButton)
        self.checkboxLayout.addWidget(self.roundWinnerRadioButton)

        self.roundPhaseClearedCheckbox = QCheckBox(self)
        self.checkboxLayout.addWidget(self.roundPhaseClearedCheckbox)

        self.roundScore = Phase10ScoreSpinBox(self)
        self.roundScore.setMaximumWidth(90)
        self.roundScore.valueChanged.connect(self.updateRoundPhaseCleared)
        self.lowerLayout.addWidget(self.roundScore)

        self.roundWinnerRadioButton.toggled.connect(
            self.roundScore.setDisabled)
        self.roundWinnerRadioButton.toggled.connect(
            self.roundPhaseClearedCheckbox.setDisabled)
        self.roundWinnerRadioButton.toggled.connect(
            self.roundPhaseClearedCheckbox.setChecked)
        self.roundWinnerRadioButton.toggled.connect(self.roundWinnerSetAction)

        self.retranslateUI()

    def retranslateUI(self):
        self.roundWinnerRadioButton.setText(
            i18n("Phase10PlayerWidget", "Winner"))
        self.roundPhaseClearedCheckbox.setText(
            i18n("Phase10PlayerWidget", "Completed"))
        self.updatePhaseName()

    def updateDisplay(self, points, completed_phases, remaining_phases):
        if len(remaining_phases) == 0:
            self.current_phase = 0
        else:
            self.current_phase = min(remaining_phases)

        self.roundWinnerRadioButton.setDown(True)
        if points >= 1000:
            self.scoreLCD.setNumDigits(4)
        self.scoreLCD.display(points)
        self.roundScore.setValue(5)
        self.roundScore.clear()
        self.roundPhaseClearedCheckbox.setChecked(False)

        for phase, label in enumerate(self.phaseLabels, start=1):
            if phase == self.current_phase and not self.engine.getWinner():
                if not label.isCurrent():
                    label.setCurrent()
            elif phase in completed_phases:
                if not label.isPassed():
                    label.setPassed()
            else:
                if not label.isRemaining():
                    label.setRemaining()
        self.updatePhaseName()

    def getScore(self):
        if self.isRoundWinner():
            return 0
        try:
            return int(self.roundScore.value())
        except Exception:
            return -1

    def switchPhasesInOrder(self, in_order):
        self.phases_in_order = in_order
        if not self.phases_in_order:
            return
        self.phaseLabels[self.current_phase-1].setRemaining()
        for label in self.phaseLabels:
            if label.isRemaining():
                label.setCurrent()
                self.current_phase = label.getNumber()
                break

    def updatePhaseSelected(self, phaselabel):
        if phaselabel.isRemaining():
            self.current_phase = phaselabel.getNumber()
            for label in self.phaseLabels:
                if label.isCurrent():
                    label.setRemaining()
            phaselabel.setCurrent()
        self.updatePhaseName()

    def updatePhaseName(self):
        phasenames = getPhaseNames(self.engine.getPhases())
        self.phaseNameLabel.setText(phasenames[self.current_phase-1])

    def updateRoundPhaseCleared(self, value):
        try:
            score = int(self.roundScore.text())
        except Exception:
            self.roundPhaseClearedCheckbox.setChecked(False)
            return

        if score < 0:
            if not self.roundWinnerRadioButton.isChecked():
                self.roundPhaseClearedCheckbox.setChecked(False)
            return

        if (score % 5 != 0):
            return

        if (score >= 50):
            self.roundWinnerRadioButton.setChecked(False)
            self.roundPhaseClearedCheckbox.setChecked(False)
        elif (score == 0):
            self.roundWinnerRadioButton.setChecked(True)
            self.roundPhaseClearedCheckbox.setChecked(True)
        else:
            self.roundWinnerRadioButton.setChecked(False)
            self.roundPhaseClearedCheckbox.setChecked(True)

    def mousePressEvent(self, event):
        child = self.childAt(event.pos())
        if child is None:
            self.roundScore.setFocus()
        elif type(child) == Phase10Label and not self.phases_in_order:
            self.updatePhaseSelected(child)
        return QGroupBox.mousePressEvent(self, event)
#

    def isRoundWinner(self): return self.roundWinnerRadioButton.isChecked()

    def getRoundPhase(self): return self.current_phase

    def isRoundCleared(self): return self.roundPhaseClearedCheckbox.isChecked()

    def roundWinnerSetAction(self, isset):
        if isset:
            self.roundWinnerSet.emit(self.player)

    def reset(self): pass

    def finish(self):
        self.roundWinnerRadioButton.toggled.disconnect(
            self.roundScore.setDisabled)
        self.roundWinnerRadioButton.toggled.disconnect(
            self.roundPhaseClearedCheckbox.setDisabled)
        self.roundWinnerRadioButton.toggled.disconnect(
            self.roundPhaseClearedCheckbox.setChecked)
        self.roundWinnerRadioButton.toggled.disconnect(
            self.roundWinnerSetAction)
        self.roundWinnerRadioButton.setDisabled(True)
        self.roundPhaseClearedCheckbox.setDisabled(True)
        self.roundScore.setDisabled(True)

    def setColour(self, colour):
        self.pcolour = colour
        css = ("QGroupBox {{ font-size: 28px; font-weight: bold;"
               "color:rgb({},{},{});}}")
        self.setStyleSheet(css.format(self.pcolour.red(),
                                      self.pcolour.green(),
                                      self.pcolour.blue()))
示例#40
0
class Calendar(QWidget):
    # keep the current time as class variable for reference
    currentDay = datetime.now().day
    currentMonth = datetime.now().month
    currentYear = datetime.now().year

    def __init__(self):
        super().__init__()
        folder = path.dirname(__file__)
        self.icon_folder = path.join(folder, "icons")

        self.setWindowTitle("Planner")
        self.setWindowIcon(
            QtGui.QIcon(path.join(self.icon_folder, 'window.png')))

        self.setGeometry(300, 200, 600, 400)
        self.initUI()

    def initUI(self):
        self.calendar = QCalendarWidget()
        self.calendar.setGeometry(0, 0, 300, 300)
        self.calendar.setGridVisible(True)

        # don't allow going back to past months in calendar
        self.calendar.setMinimumDate(
            QDate(self.currentYear, self.currentMonth, 1))

        # format for dates in calendar that have events
        self.fmt = QTextCharFormat()
        self.fmt.setBackground(QColor(255, 165, 0, 100))

        # format for the current day
        cur_fmt = QTextCharFormat()
        cur_fmt.setBackground(QColor(0, 255, 90, 70))

        # format to change back to if all events are deleted
        self.delfmt = QTextCharFormat()
        self.delfmt.setBackground(Qt.transparent)

        # check if json file exists, if it does load the data from it
        file_exists = path.isfile(
            path.join(path.dirname(__file__), "data.json"))
        if file_exists:
            with open("data.json", "r") as json_file:
                self.data = json.load(json_file)
        else:
            self.data = {}

        # delete data from days prior to the current day
        cur = QDate.currentDate()
        for date in list(self.data.keys()):
            check_date = QDate.fromString(date, "dMyyyy")
            if cur.daysTo(check_date) <= 0 and cur != check_date:
                self.data.pop(date)
            else:
                self.calendar.setDateTextFormat(check_date, self.fmt)

        # mark current day in calendar
        current = str(self.currentDay) + str(self.currentMonth) + str(
            self.currentYear)
        self.calendar.setDateTextFormat(QDate.fromString(current, "dMyyyy"),
                                        cur_fmt)

        # organize buttons and layouts for display
        addButton = QPushButton("Add Event")
        addButton.clicked.connect(self.addNote)
        editButton = QPushButton("Edit")
        editButton.clicked.connect(self.editNote)
        delButton = QPushButton("Delete")
        delButton.clicked.connect(self.delNote)

        self.calendar.selectionChanged.connect(self.showDateInfo)
        self.calendar.selectionChanged.connect(self.labelDate)
        self.calendar.selectionChanged.connect(self.highlightFirstItem)

        self.note_group = QListWidget()
        self.note_group.setSortingEnabled(True)
        self.note_group.setStyleSheet("QListView::item {height: 40px;}")

        self.label = QLabel()
        label_font = QtGui.QFont("Gabriola", 18)
        self.label.setFont(label_font)
        self.labelDate()
        self.showDateInfo()

        labelp = QLabel()
        pixmap = QPixmap(path.join(self.icon_folder, 'calendar.png'))
        labelp.setPixmap(pixmap)

        # set up a timer that automatically updates every second
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Filled)
        self.lcd.setMinimumWidth(80)
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)
        self.showTime()

        hbox1 = QHBoxLayout()
        hbox1.addStretch(1)
        hbox1.addWidget(self.label)
        hbox1.addStretch(1)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(addButton)
        hbox2.addWidget(editButton)
        hbox2.addWidget(delButton)

        hbox3 = QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(labelp)
        hbox3.addWidget(self.lcd)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addWidget(self.note_group)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)

        hbox = QHBoxLayout()
        hbox.addWidget(self.calendar)
        hbox.addLayout(vbox)

        self.setLayout(hbox)

    def showDateInfo(self):
        # add events to selected date
        date = self.getDate()
        self.note_group.clear()
        if date in self.data:
            self.note_group.addItems(self.data[date])

    def addNote(self):
        # adding notes for selected date
        # if a note starts with any number other than 0, 1, 2
        # add a 0 before it so that we can easily sort events
        # by start time
        date = self.getDate()
        row = self.note_group.currentRow()
        title = "Add {}".format("event")
        string, ok = QInputDialog.getText(self, title, title)

        if ok and string:
            if string[0].isdigit() and string[0] not in ["0", "1", "2"]:
                string = string.replace(string[0], "0" + string[0])
            self.note_group.insertItem(row, string)
            self.calendar.setDateTextFormat(QDate.fromString(date, "dMyyyy"),
                                            self.fmt)
            if date in self.data:
                self.data[date].append(string)
            else:
                self.data[date] = [string]

    def delNote(self):
        # delete the currently selected item
        date = self.getDate()
        row = self.note_group.currentRow()
        item = self.note_group.item(row)

        if not item:
            return
        reply = QMessageBox.question(self, "Remove", "Remove",
                                     QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            item = self.note_group.takeItem(row)
            self.data[date].remove(item.text())
            if not self.data[date]:
                del (self.data[date])
                self.calendar.setDateTextFormat(
                    QDate.fromString(date, "dMyyyy"), self.delfmt)
            del (item)

    def editNote(self):
        # edit the currently selected item
        date = self.getDate()
        row = self.note_group.currentRow()
        item = self.note_group.item(row)

        if item:
            copy = item.text()
            title = "Edit event"
            string, ok = QInputDialog.getText(self, title, title,
                                              QLineEdit.Normal, item.text())

            if ok and string:
                self.data[date].remove(copy)
                self.data[date].append(string)
                if string[0].isdigit() and string[0] not in ["0", "1", "2"]:
                    string = string.replace(string[0], "0" + string[0])
                item.setText(string)

    def getDate(self):
        # parse the selected date into usable string form
        select = self.calendar.selectedDate()
        date = str(select.day()) + str(select.month()) + str(select.year())
        return date

    def labelDate(self):
        # label to show the long name form of the selected date
        # format US style like "Thursday, February 20, 2020"
        select = self.calendar.selectedDate()
        weekday, month = select.dayOfWeek(), select.month()
        day, year = str(select.day()), str(select.year())
        week_day, word_month = QDate.longDayName(weekday), QDate.longMonthName(
            month)
        self.label.setText(week_day + ", " + word_month + " " + day + ", " +
                           year)

    def highlightFirstItem(self):
        # highlight the first item immediately after switching selection
        if self.note_group.count() > 0:
            self.note_group.setCurrentRow(0)

    def showTime(self):
        # keep the current time updated
        time = QTime.currentTime()
        text = time.toString("hh:mm")
        if time.second() % 2 == 0:
            text.replace(text[2], '')
        self.lcd.display(text)

    def closeEvent(self, e):
        # save all data into json file when user closes app
        with open("data.json", "w") as json_file:
            json.dump(self.data, json_file)
        e.accept()
示例#41
0
    def initUI(self):
        # Инициализация элементов GUI

        radio_button_circle = QRadioButton('Круг')
        radio_button_circle.setChecked(True)
        radio_button_square = QRadioButton('Квадрат')
        radio_button_triangle = QRadioButton('Треугольник')

        combo_box_color = QComboBox()
        combo_box_color.addItems(['Белый', 'Черный', 'Зеленый', 'Синий', 'Красный'])

        label_rotate = QLabel('Поворот')
        label_size = QLabel('Размер')
        label_move_y = QLabel('Перемещение: ось Y')
        label_move_x = QLabel('Перемещение: ось X')

        horizontal_slider_rotate = QSlider(Qt.Horizontal, self)
        horizontal_slider_rotate.setMaximum(360)

        horizontal_slider_size = QSlider(Qt.Horizontal, self)
        horizontal_slider_size.setProperty("value", 50)

        horizontal_slider_move_x = QSlider(Qt.Horizontal, self)
        horizontal_slider_move_x.setMaximum(500)
        horizontal_slider_move_x.setProperty("value", 0)

        horizontal_slider_move_y = QSlider(Qt.Horizontal, self)
        horizontal_slider_move_y.setMaximum(500)
        horizontal_slider_move_y.setProperty("value", 0)

        lcd_number_rotate = QLCDNumber()
        lcd_number_rotate.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
        lcd_number_rotate.setProperty("intValue", 0)

        lcd_number_size = QLCDNumber()
        lcd_number_size.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
        lcd_number_size.setProperty("intValue", 50)

        lcd_number_move_x = QLCDNumber()
        lcd_number_move_x.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
        lcd_number_move_x.setProperty("intValue", 0)

        lcd_number_move_y = QLCDNumber()
        lcd_number_move_y.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
        lcd_number_move_y.setProperty("intValue", 0)

        # Инициадизация графической сцены
        graphics_view = QGraphicsView()
        scene = QGraphicsScene()
        graphics_view.setScene(scene)

        # Применение варианта расположения элементов GUI
        grid = QGridLayout()
        grid.setSpacing(10)

        # Добавление элементов GUI
        grid.addWidget(radio_button_circle, 0, 0)
        grid.addWidget(label_rotate, 0, 1)
        grid.addWidget(horizontal_slider_rotate, 0, 2)
        grid.addWidget(lcd_number_rotate, 0, 3)

        grid.addWidget(radio_button_square, 1, 0)
        grid.addWidget(label_size, 1, 1)
        grid.addWidget(horizontal_slider_size, 1, 2)
        grid.addWidget(lcd_number_size, 1, 3)

        grid.addWidget(radio_button_triangle, 2, 0)
        grid.addWidget(label_move_x, 2, 1)
        grid.addWidget(horizontal_slider_move_x, 2, 2)
        grid.addWidget(lcd_number_move_x, 2, 3)

        grid.addWidget(combo_box_color, 3, 0)
        grid.addWidget(label_move_y, 3, 1)
        grid.addWidget(horizontal_slider_move_y, 3, 2)
        grid.addWidget(lcd_number_move_y, 3, 3)

        grid.addWidget(graphics_view, 4, 0, 4, 4)

        # Связь элементов GUI между собой
        horizontal_slider_size.valueChanged.connect(lcd_number_size.display)
        horizontal_slider_rotate.valueChanged.connect(lcd_number_rotate.display)
        horizontal_slider_move_x.valueChanged.connect(lcd_number_move_x.display)
        horizontal_slider_move_y.valueChanged.connect(lcd_number_move_y.display)

        def rotate():
            # получение значения со слайдера
            r = horizontal_slider_rotate.sliderPosition()
            # получение статуса радиокнопок и выполнение нужного действия
            if radio_button_circle.isChecked():
                circle1.rotate_circle(r)
            elif radio_button_square.isChecked():
                square1.rotate_square(r)
            elif radio_button_triangle.isChecked():
                triangle1.rotate_triangle(r)
            else:
                print('error')
            print('rotate: ', r)

        def move():
            # получение значения со слайдера
            m = horizontal_slider_move_x.sliderPosition()
            n = horizontal_slider_move_y.sliderPosition()
            # получение статуса радиокнопок и выполнение нужного действия
            if radio_button_circle.isChecked():
                circle1.move_circle(m, n)
            elif radio_button_square.isChecked():
                square1.move_square(m, n)
            elif radio_button_triangle.isChecked():
                triangle1.move_triangle(m, n)
            else:
                print('error')
            print('move: ', m, ' : ', n)

        def scale():
            # получение значения со слайдера
            s = horizontal_slider_size.sliderPosition()
            # получение статуса радиокнопок и выполнение нужного действия
            if radio_button_circle.isChecked():
                circle1.scale_circle(s)
            elif radio_button_square.isChecked():
                square1.scale_square(s)
            elif radio_button_triangle.isChecked():
                triangle1.scale_triangle(s)
            else:
                print('error')
            print('scale: ', s)

        def recolor():
            # получение значения с комбобокса
            color = combo_box_color.currentText()

            if color == 'Белый':
                r = 255
                g = 255
                b = 255
            elif color == 'Черный':
                r = 0
                g = 0
                b = 0
            elif color == 'Зеленый':
                r = 0
                g = 255
                b = 0
            elif color == 'Синий':
                r = 0
                g = 0
                b = 255
            elif color == 'Красный':
                r = 255
                g = 0
                b = 0
            else:
                r = 0
                g = 0
                b = 0

            # получение статуса радиокнопок и выполнение нужного действия
            if radio_button_circle.isChecked():
                circle1.recolor_circle(r, g, b)
            elif radio_button_square.isChecked():
                square1.recolor_square(r, g, b)
            elif radio_button_triangle.isChecked():
                triangle1.recolor_triangle(r, g, b)
            else:
                print('error')
            print('recolor: ', color)

        # Отрисовка

        square1 = Square(0, 0, 250, 250)
        square1.draw_square(scene)

        circle1 = Сircle(0, 0, 250, 250)
        circle1.draw_circle(scene)

        triangle1 = Triangle(0, 0, 0, 250, 250, 250)
        triangle1.draw_triangle(scene)

        # Активация функций слайдерами и комбобоксу
        horizontal_slider_rotate.valueChanged.connect(rotate)
        horizontal_slider_size.valueChanged.connect(scale)
        horizontal_slider_move_x.valueChanged.connect(move)
        horizontal_slider_move_y.valueChanged.connect(move)
        combo_box_color.currentTextChanged.connect(recolor)

        self.setLayout(grid)
        self.setGeometry(0, 0, 700, 700)
        self.setWindowTitle('Review')
        self.show()
示例#42
0
class UiGameFrame(QFrame):
    def __init__(self, parent):
        super(UiGameFrame, self).__init__(parent)
        self.setupUi()

    def setupUi(self):

        # 游戏界面
        self.setGeometry(QRect(10, 10, 671, 711))
        # self.setStyleSheet("background-image: url(./img/bg.bmp);")
        self.setFrameShape(QFrame.Box)
        self.setFrameShadow(QFrame.Sunken)
        self.setLineWidth(2)
        self.setObjectName("uiGameFrame")

        # 房间信息
        self.game_info = QLabel(self)
        self.game_info.setGeometry(QRect(20, 5, 631, 40))
        self.game_info.setObjectName("gameInfo")
        self.game_info.setScaledContents(True)
        self.game_info.setStyleSheet(
            'font-size:20px;font-weight:bold;')
        self.game_info.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        # 游戏画面
        self.game_frame = QFrame(self)
        self.game_frame.setGeometry(QRect(80, 145, 504, 504))
        # self.game_frame.setStyleSheet("background-image: url(./img/game.bmp);")
        self.game_frame.setFrameShape(QFrame.Box)
        self.game_frame.setFrameShadow(QFrame.Plain)
        self.game_frame.setObjectName("gameFrame")

        # 对战
        self.vs_frame = QFrame(self)
        self.vs_frame.setGeometry(QRect(50, 55, 270, 80))
        self.vs_frame.setFrameShape(QFrame.StyledPanel)
        self.vs_frame.setFrameShadow(QFrame.Raised)
        self.vs_frame.setObjectName("vsFrame")
        # self.vs_frame.setStyleSheet("border:1px solid;")

        self.vs_user_image = QLabel(self.vs_frame)
        self.vs_user_image.setGeometry(QRect(5, 5, 70, 70))
        self.vs_user_image.setObjectName("vsUserImage")
        self.vs_user_image.setScaledContents(True)

        self.vs_user_info = QLabel(self.vs_frame)
        self.vs_user_info.setGeometry(QRect(80, 5, 120, 70))
        self.vs_user_info.setObjectName("vsUserInfo")

        self.lcdNumber_l = QLCDNumber(self.vs_frame)
        self.lcdNumber_l.setGeometry(QRect(205, 5, 60, 70))
        self.lcdNumber_l.setLineWidth(0)
        self.lcdNumber_l.setDigitCount(2)
        self.lcdNumber_l.setSegmentStyle(QLCDNumber.Flat)
        self.lcdNumber_l.setProperty("intValue", 20)
        self.lcdNumber_l.setObjectName("lcdNumber_2")

        self.vs_frame_r = QFrame(self)
        self.vs_frame_r.setGeometry(QRect(350, 55, 270, 80))
        self.vs_frame_r.setFrameShape(QFrame.StyledPanel)
        self.vs_frame_r.setFrameShadow(QFrame.Raised)
        self.vs_frame_r.setObjectName("vsFrameR")
        # self.vs_frame_r.setStyleSheet("border:1px solid;")

        self.lcdNumber_r = QLCDNumber(self.vs_frame_r)
        self.lcdNumber_r.setGeometry(QRect(5, 5, 60, 70))
        self.lcdNumber_r.setLineWidth(0)
        self.lcdNumber_r.setDigitCount(2)
        self.lcdNumber_r.setSegmentStyle(QLCDNumber.Flat)
        self.lcdNumber_r.setProperty("intValue", 20)
        self.lcdNumber_r.setObjectName("lcdNumber_3")

        self.vs_user_image_r = QLabel(self.vs_frame_r)
        self.vs_user_image_r.setGeometry(QRect(70, 5, 70, 70))
        self.vs_user_image_r.setObjectName("vsUserImageR")
        self.vs_user_image_r.setScaledContents(True)

        self.vs_user_info_r = QLabel(self.vs_frame_r)
        self.vs_user_info_r.setGeometry(QRect(145, 5, 120, 70))
        self.vs_user_info_r.setObjectName("vsUserInfoR")

        # 按钮区域
        self.cmd_frame = QFrame(self)
        self.cmd_frame.setGeometry(QRect(55, 655, 560, 47))
        self.cmd_frame.setFrameShape(QFrame.StyledPanel)
        self.cmd_frame.setFrameShadow(QFrame.Raised)
        self.cmd_frame.setObjectName("cmdFrame")
        # 开始按钮
        self.gameStartBtn = QPushButton(self.cmd_frame)
        self.gameStartBtn.setGeometry(QRect(10, 10, 100, 27))
        self.gameStartBtn.setObjectName("gameStartBtn")

        # 悔棋按钮
        self.gameUndoBtn = QPushButton(self.cmd_frame)
        self.gameUndoBtn.setGeometry(QRect(120, 10, 100, 27))
        self.gameUndoBtn.setObjectName("gameUndoBtn")

        # 认输按钮
        self.gameGiveupBtn = QPushButton(self.cmd_frame)
        self.gameGiveupBtn.setGeometry(QRect(230, 10, 100, 27))
        self.gameGiveupBtn.setObjectName("gameGiveupBtn")

        # 返回大厅
        self.gameReHallBtn = QPushButton(self.cmd_frame)
        self.gameReHallBtn.setGeometry(QRect(340, 10, 100, 27))
        self.gameReHallBtn.setObjectName("gameReHallBtn")

        # 设置
        self.gameSetBtn = QPushButton(self.cmd_frame)
        self.gameSetBtn.setGeometry(QRect(450, 10, 100, 27))
        self.gameSetBtn.setObjectName("gameSetBtn")

        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.gameStartBtn.setText(_translate("MainWindow", "开始游戏"))
        self.gameUndoBtn.setText(_translate("MainWindow", "悔棋"))
        self.gameGiveupBtn.setText(_translate("MainWindow", "认输"))
        self.gameReHallBtn.setText(_translate("MainWindow", "返回大厅"))
        self.gameSetBtn.setText(_translate("MainWindow", "设置"))
class PlayingMediaWidget(QWidget):

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

        self.cue = cue
        self.media_time = media_time

        self._dbmeter_element = None
        self._accurate_time = False

        scroll_size = (self.parent().verticalScrollBar().width() + 5)
        self.setGeometry(0, 0, self.parent().width() - scroll_size, 102)
        self.setFocusPolicy(Qt.NoFocus)

        self.gridLayoutWidget = QWidget(self)
        self.gridLayoutWidget.setGeometry(self.geometry())
        self.gridLayout = QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(2, 2, 2, 2)

        self.nameLabel = QLabel(self.gridLayoutWidget)
        self.nameLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.nameLabel.setText(cue['name'])
        self.nameLabel.setToolTip(cue['name'])
        self.gridLayout.addWidget(self.nameLabel, 0, 0, 1, 3)

        self.playPauseButton = QPushButton(self.gridLayoutWidget)
        self.playPauseButton.setSizePolicy(QSizePolicy.Ignored,
                                           QSizePolicy.Ignored)
        self.playPauseButton.setIcon(QIcon.fromTheme("media-playback-pause"))
        self.playPauseButton.setFocusPolicy(Qt.NoFocus)
        self.playPauseButton.clicked.connect(lambda: self.cue.media.pause())
        self.gridLayout.addWidget(self.playPauseButton, 1, 0)

        self.stopButton = QPushButton(self.gridLayoutWidget)
        self.stopButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.stopButton.setIcon(QIcon.fromTheme("media-playback-stop"))
        self.stopButton.setFocusPolicy(Qt.NoFocus)
        self.stopButton.clicked.connect(lambda m: cue.media.stop())
        self.gridLayout.addWidget(self.stopButton, 1, 1)

        self.timeDisplay = QLCDNumber(self.gridLayoutWidget)
        self.timeDisplay.setSegmentStyle(QLCDNumber.Flat)
        self.timeDisplay.setDigitCount(8)
        self.timeDisplay.display(strtime(cue.media['duration']))
        self.gridLayout.addWidget(self.timeDisplay, 1, 2)

        self.seekSlider = QClickSlider(self.gridLayoutWidget)
        self.seekSlider.setOrientation(Qt.Horizontal)
        self.seekSlider.setRange(0, cue.media['duration'])
        self.seekSlider.setFocusPolicy(Qt.NoFocus)
        self.seekSlider.sliderMoved.connect(cue.media.seek)
        self.seekSlider.sliderJumped.connect(cue.media.seek)
        self.seekSlider.setVisible(False)

        self.dbmeter = QDbMeter(self.gridLayoutWidget)
        self.dbmeter.setVisible(False)

        self.gridLayout.setRowStretch(0, 1)
        self.gridLayout.setRowStretch(1, 2)
        self.gridLayout.setColumnStretch(0, 3)
        self.gridLayout.setColumnStretch(1, 3)
        self.gridLayout.setColumnStretch(2, 5)

        self.media_time.notify.connect(self.on_time_updated)

        cue.updated.connect(self.on_cue_updated)
        cue.media.duration.connect(self.update_duration)
        cue.media.played.connect(self._pause_to_play)
        cue.media.paused.connect(self._play_to_pause)

        self.fade = self.cue.media.element("Fade")
        if self.fade is not None:
            self.fade.enter_fadein.connect(self.enter_fadein)
            self.fade.enter_fadeout.connect(self.enter_fadeout)
            self.fade.exit_fadein.connect(self.exit_fade)
            self.fade.exit_fadeout.connect(self.exit_fade)

    def enter_fadeout(self):
        p = self.timeDisplay.palette()
        p.setColor(p.Text, QColor(255, 50, 50))
        self.timeDisplay.setPalette(p)

    def enter_fadein(self):
        p = self.timeDisplay.palette()
        p.setColor(p.Text, QColor(0, 255, 0))
        self.timeDisplay.setPalette(p)

    def exit_fade(self):
        self.timeDisplay.setPalette(self.palette())

    def on_cue_updated(self, cue):
        self.nameLabel.setText(cue['name'])
        self.nameLabel.setToolTip(cue['name'])

    def set_accurate_time(self, enable):
        self._accurate_time = enable

    def set_seek_visible(self, visible):
        if visible and not self.seekSlider.isVisible():
            self.gridLayout.addWidget(self.seekSlider, 2, 0, 1, 3)
            self.gridLayout.setRowStretch(2, 1)
        elif not visible and self.seekSlider.isVisible():
            self.gridLayout.removeWidget(self.seekSlider)
            self.gridLayout.setRowStretch(2, 0)

        self.seekSlider.setVisible(visible)

    def set_dbmeter_visible(self, visible):
        if self._dbmeter_element is not None:
            self._dbmeter_element.levelReady.disconnect(self.dbmeter.plot)
            self._dbmeter_element = None

        if visible:
            self._dbmeter_element = self.cue.media.element("DbMeter")
            if self._dbmeter_element is not None:
                self._dbmeter_element.levelReady.connect(self.dbmeter.plot)

        # Add/Remove the QDbMeter in the layout
        if visible and not self.dbmeter.isVisible():
            self.gridLayout.addWidget(self.dbmeter, 0, 3, 4, 1)
            self.gridLayout.setColumnStretch(3, 1)
        elif not visible and self.dbmeter.isVisible():
            self.gridLayout.removeWidget(self.dbmeter)
            self.gridLayout.setColumnStretch(3, 0)

        self.dbmeter.setVisible(visible)

    def on_time_updated(self, time):
        if not self.visibleRegion().isEmpty():
            # If the given value is the duration or < 0 set the time to 0
            if time == self.cue.media['duration'] or time < 0:
                time = 0

            # Set the value the seek slider
            self.seekSlider.setValue(time)

            # If in count-down mode the widget will show the remaining time
            time = self.cue.media['duration'] - time

            # Show the time in the widget
            self.timeDisplay.display(strtime(time,
                                             accurate=self._accurate_time))

    def update_duration(self, media, duration):
        self.seekSlider.setMaximum(duration)

    def _play_to_pause(self):
        self.playPauseButton.clicked.disconnect()
        self.playPauseButton.clicked.connect(lambda: self.cue.media.play())
        self.playPauseButton.setIcon(QIcon.fromTheme("media-playback-start"))

    def _pause_to_play(self):
        self.playPauseButton.clicked.disconnect()
        self.playPauseButton.clicked.connect(lambda: self.cue.media.pause())
        self.playPauseButton.setIcon(QIcon.fromTheme("media-playback-pause"))

    def destroy_widget(self):
        self.hide()
        self.set_dbmeter_visible(False)
        self.media_time.notify.disconnect(self.on_time_updated)

        if self.fade is not None:
            self.fade.enter_fadein.disconnect(self.enter_fadein)
            self.fade.enter_fadeout.disconnect(self.enter_fadeout)
            self.fade.exit_fadein.disconnect(self.exit_fade)
            self.fade.exit_fadeout.disconnect(self.exit_fade)

        self.cue.media.duration.disconnect(self.update_duration)
        self.cue.updated.disconnect(self.on_cue_updated)
class SinglePlayerGame(QWidget):
    def __init__(self, difficulty=1, numberOfGames=1):
        super(SinglePlayerGame, self).__init__()
        self.difficulty = difficulty
        self.numberOfGames = numberOfGames
        self.gamesPlayed = 0
        self.playerScore = 0
        self.opponentScore = 0
        self.playerIsNotFirst = False

        self.gamesCounter = QLabel()
        self.gamesCounter.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.updateGameCounter()

        mainLayout = QVBoxLayout()

        self.gameWidget = BotGame(self.getOpponent())
        self.gameWidget.gameEnded.connect(self.updateScoreAndReset)
        self.saveButton = QPushButton('Save series')
        self.saveButton.clicked.connect(self.saveGame)
        self.message = self.createLabel('')
        self.message.hide()
        mainLayout.addLayout(self.createScoreLayout())
        mainLayout.addWidget(self.gameWidget)
        mainLayout.addWidget(self.message)
        pack = self.packInHStretch([self.gamesCounter, self.saveButton])
        mainLayout.addLayout(pack)
        self.setLayout(mainLayout)

    def createScoreLayout(self):
        self.playerScoreLcd = QLCDNumber(2)
        self.playerScoreLcd.setSegmentStyle(QLCDNumber.Filled)
        self.playerScoreLcd.setMinimumSize(75, 50)
        self.playerScoreLcd.display(0)
        self.opponentScoreLcd = QLCDNumber(2)
        self.opponentScoreLcd.setSegmentStyle(QLCDNumber.Filled)
        self.opponentScoreLcd.setMinimumSize(75, 50)
        self.opponentScoreLcd.display(0)
        layout = QHBoxLayout()
        layout.addStretch(1)
        layout.addWidget(self.createLabel('You: '))
        layout.addWidget(self.playerScoreLcd)
        layout.addStretch(1)
        layout.addWidget(self.createLabel('Opponent: '))
        layout.addWidget(self.opponentScoreLcd)
        layout.addStretch(1)
        return layout

    def packInHStretch(self, widgets):
        layout = QHBoxLayout()
        layout.addStretch(1)
        for widget in widgets:
            layout.addWidget(widget)
            layout.addStretch(1)
        return layout

    def displayMessage(self, message):
        self.message.setText(message)
        self.message.show()
        self.repaint()

    def hideMessage(self):
        self.message.hide()
        self.repaint()

    def updateScoreAndReset(self):
        self.gamesPlayed += 1
        self.playerIsNotFirst = not self.playerIsNotFirst
        result = self.gameWidget.board.state
        message = ''
        if result == game.boards.State.X_WON:
            self.playerScore += 3
            message = 'Congrats! You won the game!'
        elif result == game.boards.State.O_WON:
            self.opponentScore += 3
            message = 'Sorry! You lost the game!'
        elif result == game.boards.State.DRAW:
            self.playerScore += 1
            self.opponentScore += 1
            message = 'The game ended in a draw!'
        self.displayMessage(message)
        self.playerScoreLcd.display(self.playerScore)
        self.opponentScoreLcd.display(self.opponentScore)
        if self.numberOfGames > self.gamesPlayed:
            for i in range(3, 0, -1):
                self.displayMessage(message + ' New game starting in ' +
                                    str(i))
                time.sleep(1)
            self.hideMessage()
            self.gameWidget.reset(self.playerIsNotFirst)
            self.updateGameCounter()
        else:
            self.announceResult()

    def announceResult(self):
        if self.playerScore > self.opponentScore:
            self.displayMessage('Congrats! You won the series!')
        elif self.playerScore < self.opponentScore:
            self.displayMessage('Sorry. You lost the series!')
        else:
            self.displayMessage('The series ended in a draw!')

    def updateGameCounter(self):
        self.gamesCounter.setText('Game ' + str(self.gamesPlayed + 1) +
                                  ' of ' + str(self.numberOfGames))

    def createLabel(self, text):
        lbl = QLabel(text)
        lbl.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        font = QFont()
        font.setPointSize(12)
        lbl.setFont(font)
        return lbl

    def getOpponent(self):
        return game.players.ai.select_bot(self.difficulty)

    def saveGame(self):
        if self.gamesPlayed == self.numberOfGames:
            if self.gameWidget.board.state != game.boards.State.IN_PROGRESS:
                self.displayMessage('Cannot save. The game has ended.')
                return
        filename = QFileDialog().getSaveFileName(self, 'Save game',
                                                 'untitledgame')
        if not filename[0]:
            return
        self.displayMessage('Saving...')
        with open(filename[0], 'wb') as handle:
            pickle.dump(self.getConfiguration(), handle)
        self.displayMessage('Saved!')

    def getConfiguration(self):
        return (self.difficulty,
                self.numberOfGames,
                self.gamesPlayed,
                self.playerScore,
                self.opponentScore,
                self.playerIsNotFirst,
                self.gameWidget.board)

    def validateConfig(self, config):
        if not isinstance(config, tuple):
            return False
        if len(config) != 7:
            return False
        if not isinstance(config[0], int) or config[0] not in range(1, 5):
            return False
        if not isinstance(config[1], int) or config[1] < 1:
            return False
        if not isinstance(config[2], int) or config[2] > config[1]:
            return False
        if not isinstance(config[3], int) or config[3] < 0:
            return False
        if not isinstance(config[4], int) or config[4] < 0:
            return False
        if not isinstance(config[5], bool):
            return False
        if not isinstance(config[6], game.boards.Macroboard):
            return False
        return True

    def loadConfiguration(self, config):
        if not self.validateConfig(config):
            raise ValueError('Invalid configuration')
        self.difficulty = config[0]
        self.numberOfGames = config[1]
        self.gamesPlayed = config[2]
        self.playerScore = config[3]
        self.opponentScore = config[4]
        self.playerIsNotFirst = config[5]
        self.gameWidget.loadBoard(config[6])
        self.gameWidget.setSecondPlayer(self.getOpponent())
        self.updateGameCounter()
        self.playerScoreLcd.display(self.playerScore)
        self.opponentScoreLcd.display(self.opponentScore)