def addLCDNumbers(self): fortLCD = QLCDNumber(1, self) fortLCD.setFrameShape(QFrame.NoFrame) fortLCD.move(125, 50) fortLCD.resize(40, 40) fortLCD.display(self.square.ter.buildings.fort_lvl) incomeLCD = QLCDNumber(2, self) incomeLCD.setFrameShape(QFrame.NoFrame) incomeLCD.move(117, 10) incomeLCD.resize(40, 40) incomeLCD.display(self.square.ter.get_income()) marketLCD = QLCDNumber(1, self) marketLCD.setFrameShape(QFrame.NoFrame) marketLCD.move(125, 90) marketLCD.resize(40, 40) marketLCD.display(self.square.ter.buildings.market_lvl) self.square.incomeChanged.connect(incomeLCD.display) self.square.fortUpgr.connect(fortLCD.display) self.square.marketUpgr.connect(marketLCD.display)
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()
class timeWidget(QWidget): time = pyqtSignal() def __init__(self,winParent): super(timeWidget, self).__init__() self.winParent=winParent self.seconds = 0 hLayout = QHBoxLayout() timeLabel = QLabel("Time") self.lcd = QLCDNumber(self) self.lcd.setMaximumSize(100,50) hLayout.addWidget(timeLabel,0) hLayout.addWidget(self.lcd, 1) hSpacer = QSpacerItem(300, 30, QSizePolicy.Ignored, QSizePolicy.Ignored) hLayout.addItem(hSpacer) self.setLayout(hLayout) timer = QTimer(self) timer.start(1000) timer.timeout.connect(self.printTime) # get the palette palette = self.lcd.palette() # foreground color palette.setColor(palette.WindowText, QColor(85, 85, 255)) # background color palette.setColor(palette.Background, QColor(0, 170, 255)) # "light" border palette.setColor(palette.Light, QColor(255, 0, 0)) # "dark" border palette.setColor(palette.Dark, QColor(0, 255, 0)) # set the palette self.lcd.setPalette(palette) def printTime(self): self.seconds += 1 self.lcd.display(self.seconds)
class SpeedWidget(QtWidgets.QWidget): def __init__(self): super(SpeedWidget, self).__init__() self.initUI() def initUI(self): self.lcd = QLCDNumber(self) vbox = QVBoxLayout() vbox.addWidget(self.lcd) self.setLayout(vbox) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('WordspPerMinute') self.value = 0 self.show() # set lcd display value def setValues(self, wpm): complete = int(wpm) self.lcd.display(complete)
class LCDNumbersWidget(QWidget): def __init__(self): super().__init__() self.resize(600, 500) self.setWindowTitle("Digital Numbers Slice") self.lcd = QLCDNumber() slider = QSlider(Qt.Horizontal) slider.setMaximum(500) slider.setMinimum(-500) slider.valueChanged.connect(self.updateLCD) layout = QVBoxLayout() layout.addWidget(self.lcd) layout.addWidget(slider) self.setLayout(layout) def updateLCD(self, event): print(event) self.lcd.display(event)
class ClassMain(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.dong_ho = QLCDNumber(self) self.dong_ho.setNumDigits(8) self.dong_ho.setGeometry(10, 10, 280, 80) dem_gio = QTimer(self) dem_gio.timeout.connect(self.hien_gio) dem_gio.start(1000) self.setWindowTitle('Vsmart CARPARKING SYSTEM V.1.01') self.setWindowIcon(QIcon('clock.png')) self.resize(300, 100) #setFixedSize(300,100) self.show() def hien_gio(self): self.dong_ho.display(strftime("%H" + ":" + "%M" + ":" + "%S"))
class Channel(QWidget): def __init__(self, parent, name, x, y, value): super(Channel, self).__init__(parent) self.label = QLabel(name, self) self.label.resize(CHANNEL_WIDTH, 20) self.label.move(x, y) self.label.show() self.gauge = QLCDNumber(self) self.gauge.display(value) self.gauge.move(x, y + 10) 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()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) self.setGeometry(300, 300, 400, 300) self.setWindowTitle('Calculator') self.lcd = QLCDNumber() grid.addWidget(self.lcd, 0, 0, 3, 0) grid.setSpacing(10) names = [ 'Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+' ] positions = [(i, j) for i in range(4, 9) for j in range(4, 8)] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, *position) button.clicked.connect(self.Cli) self.move(300, 150) self.show() def Cli(self): sender = self.sender().text() ls = ['/', '.', '-', '=', '+'] if sender in ls: self.lcd.display('A') else: self.lcd.display(sender)
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() # 窗体全屏
class DigitalClock(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.initUI() def initUI(self): self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.Time) self.timer.start(10) self.clock_screen = QLCDNumber(self) self.clock_screen.resize(250,100) # Added self.lcd.move and moved the clock 30px down to make space for buttons self.clock_screen.move(0,30) self.clock_screen.display(strftime("%H" + ":" + "%M")) self.r1 = QRadioButton("Hide seconds", self) self.r1.move(10, 0) self.r2 = QRadioButton("Show seconds", self) self.r2.move(110, 0) self.r1.toggled.connect(self.woSecs) self.r2.toggled.connect(self.wSecs) # ---------Window settings -------------------------------- # Expanded window height by 30px self.setGeometry(300, 300, 250, 130) self.setWindowTitle("Digital Clock") self.setWindowIcon(QtGui.QIcon("")) self.show() # -------- Slots ------------------------------------------ def Time(self): global var if var == True: self.clock_screen.display(strftime("%H" + ":" + "%M")) elif var == False: self.clock_screen.display(strftime("%H" + ":" + "%M" + ":" + "%S")) def wSecs(self): global var var = False self.resize(375, 130) self.clock_screen.resize(375, 100) self.clock_screen.setDigitCount(8) def woSecs(self): global var var = True self.resize(250, 130) self.clock_screen.resize(250, 100) self.clock_screen.setDigitCount(5)
def __init__(self): super(MyWindow, self).__init__() self.initGUI("PyQt5 学习 LCDNumber") mainLayout = QGridLayout() self.setLayout(mainLayout) # 要展示的数据 price = 13.568 amount = 213 id = "18726345" lbl_price = QLabel("价格:") lbl_amount = QLabel("数量:") lbl_id = QLabel("商品编号:") lcd_price = QLCDNumber() lcd_price.setDecMode() lcd_price.setSmallDecimalPoint(True) lcd_price.display(price) mainLayout.addWidget(lbl_price, 0, 0) mainLayout.addWidget(lcd_price, 0, 1, 1, 3) lcd_amount = QLCDNumber() lcd_amount.display(amount) mainLayout.addWidget(lbl_amount, 1, 0) mainLayout.addWidget(lcd_amount, 1, 1, 1, 3) lcd_id = QLCDNumber() lcd_id.setDecMode() # NOTE: 设置能显示的数字的最大个数,如果不设置大一点,有可能显示不完整 lcd_id.setDigitCount(10) lcd_id.display(id) mainLayout.addWidget(lbl_id, 2, 0) mainLayout.addWidget(lcd_id, 2, 1, 1, 3)
class Counter(QWidget): def __init__(self, number_of_cards): super().__init__() self.cards_left = number_of_cards self.initUI() def initUI(self): self.lcd = QLCDNumber(self) grid = QGridLayout() grid.addWidget(self.lcd, 1, 0) self.setLayout(grid) self.display() def update_counter(self, cards_played): self.cards_left -= cards_played self.display() def display(self): to_display = "{}".format(self.cards_left) self.lcd.setDigitCount(len(to_display)) self.lcd.display(to_display)
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # 设置窗口属性 self.setGeometry(200, 200, 300, 300) self.setWindowTitle('格子布局') # 创建并设置格子布局 grid = QGridLayout() self.setLayout(grid) self.lcd = QLCDNumber() # 参数1:控件名 ,参数2:行,参数3:列,参数4:占用的行数,参数5:占用的列数,参数6:对齐方式 grid.addWidget(self.lcd, 0, 0, 4, 0) grid.setSpacing(10) names = [ 'Cls', 'Bc', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+' ] positions = [(i, j) for i in range(4, 9) for j in range(4, 8)] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, position[0], position[1], 1, 1) # grid.addWidget(button, *position) button.clicked.connect(self.bt_cli) self.show() def bt_cli(self): sender = self.sender().text() ls = ['/', '*', '-', '=', '+'] if sender in ls: self.lcd.display("U") else: self.lcd.display(sender)
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())
class Window(QWidget): def __init__(self): super().__init__() self.title = "This is first thing" self.height = 700 self.width = 1100 self.top = 100 self.left = 200 self.iconName = "plioky.ico" self.lcd = QLCDNumber() self.vbox = QVBoxLayout() self.init_window() def init_window(self): self.setWindowIcon(QtGui.QIcon(self.iconName)) self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.vbox.addWidget(self.lcd) self.lcd.setStyleSheet("background-color:orange") self.setStyleSheet("background-color:#212f3d") button = QPushButton("Generate random number") button.clicked.connect(self.generate) button.setStyleSheet("background-color:white") self.vbox.addWidget(button) self.setLayout(self.vbox) self.show() def generate(self): rand = random.randint(0, 100) self.lcd.display(rand)
class Calculator(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) self.setGeometry(300, 300, 400, 300) self.setWindowTitle("计算器界面") self.lcd = QLCDNumber() grid.addWidget(self.lcd, 0, 0, 3, 0) grid.setSpacing(10) names = [ 'Cls', 'Bc', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+' ] positions = [(i, j) for i in range(4, 9) for j in range(0, 4)] for position, name in zip(positions, names): if name == "": continue button = QPushButton(name) grid.addWidget(button, *position) button.clicked.connect(self.click) self.show() def click(self): sender = self.sender().text() ls = ["/", "*", "+", "-"] if sender in ls: self.lcd.display("not defined") else: self.lcd.display(sender)
class FreeWindow(QWidget): def __init__(self): super().__init__() self.makeUI() def makeUI(self): self.setGeometry(0, 0, 420, 300) self.setWindowTitle( "i hate pep8 6.0, added input-box(pay-respect counter)") self.frstbtn = QPushButton("F", self) self.frstbtn.resize(125, 100) self.frstbtn.move(137, 100) self.frstbtn.clicked.connect(self.i61) self.text = QLabel(self) self.text.setText("You have already PAYED RESPECT ") self.text.move(10, 225) self.counter = QLCDNumber(self) self.counter.move(200, 225) self.text = QLabel(self) self.text.setText("- these amount of times ") self.text.move(270, 225) self.text_for_input = QLabel(self) self.text_for_input.setText("Insert here ur int step ->") self.text_for_input.move(10, 50) self.inputbox = QLineEdit(self) self.inputbox.move(200, 50) self.count = 0 def i61(self): self.count += int(self.inputbox.text()) self.counter.display(self.count)
class Window(QWidget): def __init__(self): super().__init__() self.title = "QDial" self.left = 300 self.top = 100 self.width = 500 self.height = 500 self.IconName = "Icon/python.png" self.color = 'red' self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon(self.IconName)) self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) #self.setStyleSheet('background-color:green') vbox = QVBoxLayout() self.lcd = QLCDNumber() self.lcd.setStyleSheet('background-color:green') #self.lcd.setStyleSheet('color:black') self.button = QPushButton("Random Number") self.button.clicked.connect(self.RandomGen) self.button.setStyleSheet('background-color:red') vbox.addWidget(self.lcd) vbox.addWidget(self.button) self.setLayout(vbox) self.show() def RandomGen(self): self.lcd.display(randint(10, 100))
class Timer: initsec = 30 gosec = 10 def __init__(self, maingo, layout, turn): self.lcd = QLCDNumber() self.sec = self.initsec self.turn = turn self.updui() self.lcd.setFrameStyle(QFrame.NoFrame) self.maingo = maingo self.timer = QTimer(self.maingo.goui) self.timer.timeout.connect(self.count_time) self.timer.start(1000) layout.addWidget(self.lcd) def get_stime(self, seconds): min = seconds // 60 sec = seconds % 60 return '{:0>2}'.format(min) + ':' + '{:0>2}'.format(sec) def updui(self): self.lcd.display(self.get_stime(self.sec)) def count_time(self): if not self.turn: return self.sec -= 1 self.updui() #hack if self.sec == 0 and self.maingo.protor.step == self.turn: self.maingo.protor.surrender() self.timer.stop() def go(self): self.turn = not self.turn if self.turn: self.sec += self.gosec
class ClockWidget(QWidget): def __init__(self): super().__init__() self.LCD = QLCDNumber() self.clockLayout = QHBoxLayout() self.timer = QTimer() self.initUI() self.setLayout(self.clockLayout) self.show() def initUI(self): self.timer.timeout.connect(self.refreshLCD) self.timer.start(1000) self.LCD.setDigitCount(8) self.LCD.display(strftime("%H:%M:%S")) self.clockLayout.addWidget(self.LCD) self.setMaximumSize(650, 100) def refreshLCD(self): self.LCD.display(strftime("%H:%M:%S"))
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lcd = QLCDNumber(self) sld = QSlider(Qt.Horizontal, self) vbox = QVBoxLayout() vbox.addWidget(self.lcd) vbox.addWidget(sld) self.setLayout(vbox) sld.valueChanged.connect(self.ChangedValue) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Signal and slot') self.show() def ChangedValue(self): sender = self.sender() self.lcd.display(sender.value())
def initUI(self): lcd = QLCDNumber(self) sld = QSlider(Qt.Horizontal, self) sld.setMinimum(37) sld.setMaximum(32767) sld.setValue(37) playButton = QPushButton("Play", self) vbox = QVBoxLayout() vbox.addWidget(lcd) vbox.addWidget(sld) vbox.addWidget(playButton) self.setLayout(vbox) lcd.display(37) sld.valueChanged.connect(self.change) sld.valueChanged.connect(lcd.display) playButton.clicked.connect(self.play) self.setGeometry(300, 300, 250, 180) self.setWindowTitle('Signal & slot') self.show()
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)
class Sider(QWidget): def __init__(self): QWidget.__init__(self) self.timer = QTimer(self) self.timer.start(1000) self.timer.timeout.connect(self.ontime) # lcd self.time = 0 self.lcd = QLCDNumber() # billborad self.log = QLabel(self) self.msg = "" self.count = 0 layout = QVBoxLayout() layout.addWidget(self.lcd) layout.addWidget(self.log) layout.setStretch(0, 1) layout.setStretch(1, 3) self.setLayout(layout) self.show() def ontime(self): if self.time > 0: self.time -= 1 self.lcd.display(self.time) def time_refresh(self): self.time = 60 def log_refresh(self, x, y, time): self.count += 1 self.msg += "Ai no." + str(self.count) + "| location: (" + str(x) + ", " + str(y) \ + "), time used: " + str(time) + " secs.\n" self.log.setText(self.msg)
class parameterWidget(QWidget): def __init__(self,minimum,maximum): super(parameterWidget,self).__init__() self.container = QVBoxLayout() self.container.addStretch(1) self.slider = QSlider(Qt.Horizontal, self) self.slider.setMinimum(minimum) self.slider.setMaximum(maximum) self.slider.setTickInterval(1) self.slider.setSingleStep(1) self.container.addWidget(self.slider) self.lcd = QLCDNumber() self.lcd.setFixedHeight(100) self.lcd.setFixedWidth(100) self.lcd.resize(50, 100) self.container.addWidget(self.lcd) self.lcd.setDigitCount(8) self.slider.valueChanged.connect(self.update_lcd) self.container.addStretch(1) self.setLayout(self.container) @pyqtSlot(int) def update_lcd(self,value): self.lcd.display(str(value))
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"))
class Game(QMainWindow): def __init__(self): super().__init__() self.resize(400, 430) self.setWindowTitle('Tetris') self.scores = 0 self.tetBoard = Board(self) self.lcd = QLCDNumber(self) self.tetBoard.resize(200, 415) self.layout = QHBoxLayout() self.layout.addWidget(self.tetBoard) self.layout.addWidget(self.lcd) self.lcd.move(250, 150) self.setLayout(self.layout) self.statusbar = self.statusBar() self.tetBoard.msg2statusbar[str].connect(self.statusbar.showMessage) self.tetBoard.closeMsg.connect(self.close) self.tetBoard.scoresMsg.connect(self.increase) self.tetBoard.start() self.show() def increase(self, score): self.scores += score self.lcd.display(self.scores)
class Temperature_Page(QWidget): def __init__(self): QWidget.__init__(self) self.NowTemperature = QLCDNumber(self) self.WantTemperature = QLCDNumber(self) self.SettingDial = QDial(self) self.lbNow = QLabel("현재 온도", self) self.lbWant = QLabel("희망 온도", self) self.NowFont = self.lbNow.font() self.NowFont.setPointSize(40) self.NowFont.setBold(True) self.lbNow.resize(300, 50) self.lbNow.move(50, 50) self.lbNow.setAlignment(Qt.AlignCenter) self.lbNow.setFont(self.NowFont) self.lbWant.resize(300, 50) self.lbWant.move(400, 50) self.lbWant.setAlignment(Qt.AlignCenter) self.lbWant.setFont(self.NowFont) self.NowTemperature.resize(300, 100) self.NowTemperature.move(50, 130) self.WantTemperature.resize(300, 100) self.WantTemperature.move(400, 130) self.SettingDial.resize(190, 190) self.SettingDial.setRange(-20, 20) self.SettingDial.setNotchesVisible(True) self.SettingDial.move(460, 250) self.NowTemperature.display(sensorValue) self.SettingDial.valueChanged.connect(self.WantTemperature.display)
class DigitalClock(QMAinWindow): def __init__(self): super().__init__() self.setWindowTitle('Digital Clock') self.setGeometry(400, 300, 550, 150) self.setWindowIcon(QtGui.QIcon('clock.png')) self.initUI() self.timer = QtCore.Qtimer(self) self.timer.timeout.connect(self.current_time) self.timer.start(1000) def initUI(self): self.clock_screen = QLCDNumber(self) self.clock_screen.setStyleSheet( "color: black; background-color: white") self.clock_screen.setDigitCount(8) self.clock_screen.setGeometry(QtCore.QRect(0, 0, 550, 150)) self.current_time() def current_time(self): current = time.strftime("%I:%M:%S") self.clock_screen.display(current)
class PlayTimer(QWidget): done = pyqtSignal() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_ui() def init_ui(self): self.setProperty('id', 'timer') vbox = QVBoxLayout(self) self.instructions = QLabel(self) self.instructions.setProperty("id", "timer-instruction") self.lcd = QLCDNumber(2, self) self.clock = QBasicTimer() vbox.addWidget(self.instructions) vbox.addWidget(self.lcd) vbox.setAlignment(Qt.AlignCenter) vbox.setAlignment(self.instructions, Qt.AlignCenter) def timerEvent(self, e): if self.preptime > 1: self.preptime -= 1 self.lcd.display(self.preptime) elif self.runtime == 60: self.lcd.display(self.runtime) self.runtime -= 1 self.instructions.setText("Play!") elif self.runtime > 0: self.lcd.display(self.runtime) self.runtime -= 1 else: self.clock.stop() self.done.emit() def resizeEvent(self, e): self.lcd.setFixedSize(e.size().width() // 2, e.size().height() // 2) def start_timer(self): self.preptime, self.runtime = 3, 60 self.instructions.setText("Get ready!") self.lcd.display(self.preptime) self.clock.start(1000, self)
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(450, 150, 450, 150) self.setWindowTitle('Миникалькулятор') self.btn = QPushButton('->', self) self.label1 = QLineEdit(self) self.label2 = QLineEdit(self) self.labe1 = QLabel(self) self.labe2 = QLabel(self) self.labe3 = QLabel(self) self.labe4 = QLabel(self) self.q1 = QLCDNumber(self) self.q2 = QLCDNumber(self) self.q3 = QLCDNumber(self) self.q4 = QLCDNumber(self) self.label1.move(5, 25) self.label2.move(5, 65) self.btn.resize(20, 20) self.btn.move(150, 55) self.labe1.setText("Сумма") self.labe2.setText("Разность") self.labe3.setText("Произведение") self.labe4.setText("Частность") self.labe1.move(175, 5) self.labe2.move(175, 35) self.labe3.move(175, 65) self.labe4.move(175, 95) self.q1.move(270, 5) self.q2.move(270, 35) self.q3.move(270, 65) self.q4.move(270, 95) self.btn.clicked.connect(self.nn) def nn(self): e = int(self.label1.text()) w = int(self.label2.text()) self.q1.display(e + w) self.q2.display(e - w) self.q3.display(e * w) if w != 0: self.q4.display(e / w)
def init_ui(self): widget = QWidget(self) self.setCentralWidget(widget) vbox = QVBoxLayout(widget) # 信号与槽机制 lcd = QLCDNumber(widget) slide = QSlider(Qt.Horizontal, widget) slide.valueChanged.connect(lambda value: lcd.display(value)) vbox.addWidget(lcd) vbox.addWidget(slide) x = 0 y = 0 text = "x:{0}, y:{1}".format(x, y) self.lable = QLabel(text, widget) self.setMouseTracking(True) # 开启鼠标追踪功能 vbox.addWidget(self.lable) # 事件发送者 btn1 = QPushButton("Button 1", widget) btn2 = QPushButton("Button 2", widget) btn1.clicked.connect(self.buttonClicked) btn2.clicked.connect(self.buttonClicked) vbox.addWidget(btn1) vbox.addWidget(btn2) self.status = self.statusBar() # 创建事件委托 self.c = Communicate() # 给事件委托绑定事件 self.c.closeApp.connect(self.close) widget.setLayout(vbox) self.setGeometry(500, 100, 500, 500) self.setWindowTitle("simple") self.show()
class Main(QWidget): def __init__(self): super(Main, self).__init__() self.initUI() def initUI(self): timer = QTimer(self) timer.timeout.connect(self.Time) timer.start(10) self.lcd = QLCDNumber(self) self.lcd.resize(250, 100) self.lcd.move(0, 30) self.lcd.display(strftime('%H' + ':' + '%M')) self.r1 = QRadioButton('Hide seconds', self) self.r1.move(10, 0) self.r2 = QRadioButton('Show seconds', self) self.r2.move(110, 0) self.r1.toggled.connect(self.woSecs) self.r2.toggled.connect(self.wSecs) self.setGeometry(300, 300, 250, 130) self.setWindowTitle('Clock') self.setWindowIcon(QIcon('')) self.show() def Time(self): global var if var == True: self.lcd.display(strftime('%H' + ':' + '%M')) elif var == False: self.lcd.display(strftime('%H' + ':' + '%M' + ':' + '%S')) def wSecs(self): global var var = False self.resize(375, 130) self.lcd.resize(375, 100) self.lcd.setDigitCount(8) def woSecs(self): global var var = True self.resize(250, 130) self.lcd.resize(250, 100) self.lcd.setDigitCount(5)
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)
class ShowTime(QWidget): def __init__(self, parent=None): super(ShowTime, self).__init__(parent) self.isTimeStart = False # 标记时间是否开始计时 self.lcd = QLCDNumber(self) self.lcd.setDigitCount(8) self.lcd.display("00:00:00") # 创建定时器对象和时间对象 self.timer = QTimer() # self.timeClock = QTime() # 信号与槽 # self.btn_start.clicked.connect(self.timestart) self.timer.timeout.connect(self.addtime) # self.btn_stop.clicked.connect(self.timestop) self.v_layout = QVBoxLayout() self.v_layout.addWidget(self.lcd) self.setLayout(self.v_layout) def back_to_zero(self): self.lcd.setDigitCount(8) self.lcd.display("00:00:00") def timestart(self): # 启动计时 if not self.isTimeStart: self.timeClock.setHMS(0, 0, 0) # 初始时设置时间为 00:00:00 self.timer.start(1000) # 启动定时器,定时器对象每隔一秒发射一个timeout信号 self.isTimeStart = True def addtime(self): # 计时时间增一秒,并显示在QLable上 self.timeClock = self.timeClock.addMSecs(1000) # 时间增加一秒 # self.lable_time_val.setText(self.timeClock.toString("hh:mm:ss")) # 标签显示时间 # print(self.timeClock.toString("hh:mm:ss")) self.lcd.display(self.timeClock.toString("hh:mm:ss")) # 标签显示时间 def timestop(self): # 停止计时 if self.isTimeStart: self.timer.stop() self.isTimeStart = False
class Timer(QDialog): timeout = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) self.time=0 self.timeInterval = 1000 #默认秒 self.timerUp = QTimer() self.timerUp.setInterval(self.timeInterval) self.timerUp.timeout.connect(self.updateUptime) self.timerDown = QTimer() self.timerDown.setInterval(self.timeInterval) self.timerDown.timeout.connect(self.updateDowntime) self.initUi() self.buttonStart.clicked.connect(self.timerUp.start) self.buttonStop.clicked.connect(self.timerUp.stop) self.buttonReset.clicked.connect(self.reset) self.buttonCountDown.clicked.connect(self.timerDown.start) self.buttonStopAlarm.clicked.connect(self.timerDown.stop) self.timeSpinBox.valueChanged.connect(self.settimer) def initUi(self): mainLayout = QVBoxLayout() self.setLayout(mainLayout) self.groupBox = QGroupBox("unit") self.radioButton1 = QRadioButton("s") self.radioButton1.toggled.connect(self.setUnit) self.radioButton2 = QRadioButton("0.1s") self.radioButton2.toggled.connect(self.setUnit) self.radioButton3 = QRadioButton("0.01s") self.radioButton3.toggled.connect(self.setUnit) self.radioButton4 = QRadioButton("1ms") self.radioButton4.toggled.connect(self.setUnit) self.radioButton1.setChecked(True) self.unitLayout = QHBoxLayout() self.unitLayout.addWidget(self.radioButton1) self.unitLayout.addWidget(self.radioButton2) self.unitLayout.addWidget(self.radioButton3) self.unitLayout.addWidget(self.radioButton4) self.groupBox.setLayout(self.unitLayout) mainLayout.addWidget(self.groupBox) self.buttonStart = QPushButton(self.tr("start")) mainLayout.addWidget(self.buttonStart) self.buttonStop = QPushButton(self.tr("stop")) mainLayout.addWidget(self.buttonStop) self.timeViewer = QLCDNumber() self.timeViewer.setFixedHeight(45) mainLayout.addWidget(self.timeViewer) self.timeForHuman = QLabel() mainLayout.addWidget(self.timeForHuman) self.buttonReset = QPushButton(self.tr("reset")) mainLayout.addWidget(self.buttonReset) self.timeSpinBox = QSpinBox() self.timeSpinBox.setRange(0,10000) mainLayout.addWidget(self.timeSpinBox) self.buttonCountDown = QPushButton(self.tr("countdown")) mainLayout.addWidget(self.buttonCountDown) self.buttonStopAlarm = QPushButton(self.tr("stopalarm")) mainLayout.addWidget(self.buttonStopAlarm) def setUnit(self): if self.radioButton1.isChecked(): self.timeInterval = 1000 elif self.radioButton2.isChecked(): self.timeInterval = 100 elif self.radioButton3.isChecked(): self.timeInterval = 10 elif self.radioButton1.isChecked(): self.timeInterval = 1 self.timerUp.setInterval(self.timeInterval) self.timerDown.setInterval(self.timeInterval) def updateUptime(self): self.time += 1 self.settimer(self.time) print(self.time) def updateDowntime(self): self.time =self.time-1 self.settimer(self.time) print(self.time) if self.time <=0: self.timeout.emit() def settimer(self,int): self.time=int self.timeViewer.display(self.time) if self.timeInterval ==1000: self.timeForHuman.setText(time.strftime('%H hour %M minute %S second',time.gmtime(self.time))) elif self.timeInterval ==100: self.timeForHuman.setText(time.strftime('%H hour %M minute %S second',time.gmtime(self.time/10))) elif self.timeInterval ==10: self.timeForHuman.setText(time.strftime('%H hour %M minute %S second',time.gmtime(self.time/100))) elif self.timeInterval ==1: self.timeForHuman.setText(time.strftime('%H hour %M minute %S second',time.gmtime(self.time/1000))) def reset(self): self.time=0 self.settimer(self.time)
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
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()))
class timeDigitalWidget(QWidget): time = pyqtSignal() def __init__(self,winParent, percentaje): super(timeDigitalWidget, self).__init__() self.winParent=winParent self.seconds = 900 self.pose3d = pose3d self.percentaje = percentaje self.show = False self.MAX_PERCENT = 30 self.MAX_MARK = 10 self.hLayout = QHBoxLayout() timeLabel = QLabel("Time") self.lcd = QLCDNumber(self) self.lcd.setMaximumSize(100,50) self.hLayout.addWidget(timeLabel,0) self.hLayout.addWidget(self.lcd, 1) hSpacer = QSpacerItem(300, 30, QSizePolicy.Ignored, QSizePolicy.Ignored) self.hLayout.addItem(hSpacer) self.setLayout(self.hLayout) timer = QTimer(self) timer.start(1000) timer.timeout.connect(self.printTime) # get the palette palette = self.lcd.palette() # foreground color palette.setColor(palette.WindowText, QColor(85, 85, 255)) # background color palette.setColor(palette.Background, QColor(0, 170, 255)) # "light" border palette.setColor(palette.Light, QColor(255, 0, 0)) # "dark" border palette.setColor(palette.Dark, QColor(0, 255, 0)) # set the palette self.lcd.setPalette(palette) def showMark(self): self.show = True mark = self.testPercentaje() markLabel = QLabel('Final mark: ' + str(mark)) self.hLayout.addWidget(markLabel, 0) self.setLayout(self.hLayout) def printTime(self): if self.seconds > 0: self.seconds -= 1 else: if not self.show: self.showMark() self.lcd.display(self.seconds) def testPercentaje(self): pHouse = self.percentaje.calculatePercentaje() markPerc = float(pHouse) * float(self.MAX_MARK) / float(self.MAX_PERCENT) if pHouse > self.MAX_PERCENT: markPerc = 10 return markPerc
class Ten(QWidget): def __init__(self, parent=None): super().__init__(parent) self._START = '&START' self._STOP = 'S&TOP' self._RESET = '&RESET' self._FORMAT = 'hh:mm:ss.zzz' self._widgets() self._layout() self._properties() self._connections() def _widgets(self): self.shiverTimer = QTime(0, 0, 0) self.timer = QTimer() self.timerLCDNumber = QLCDNumber() self.timerLCDNumber.setDigitCount(12) self.timerLCDNumber.display("00:00:00.000") self.stortPushButton = QPushButton(self._START) self.resetPushButton = QPushButton(self._RESET) def _layout(self): grid = QGridLayout() grid.addWidget(self.timerLCDNumber, 0, 0, 1, 2) grid.addWidget(self.stortPushButton, 1, 0) grid.addWidget(self.resetPushButton, 1, 1) self.setLayout(grid) def _properties(self): self.resize(350, 125) self.setWindowTitle('{} {}'.format(__title__, __version__)) self.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint) def _connections(self): self.timer.timeout.connect(self.showStopwatch) self.stortPushButton.clicked.connect(self.on_stortPushButton_clicked) self.resetPushButton.clicked.connect(self.on_resetPushButton_clicked) def showStopwatch(self): """ Event handler for showing elapsed time, just like a stopwatch """ self.shiverTimer = self.shiverTimer.addMSecs(1) text = self.shiverTimer.toString(self._FORMAT) self.timerLCDNumber.display(text) def on_stortPushButton_clicked(self): if self.stortPushButton.text() == self._START: self.timer.start(1) # Start the timer self.stortPushButton.setText(self._STOP) else: self.timer.stop() # Stop the timer self.stortPushButton.setText(self._START) def on_resetPushButton_clicked(self): self.timer.stop() self.shiverTimer = QTime(0, 0, 0) self.timerLCDNumber.display(self.shiverTimer.toString(self._FORMAT)) if self.stortPushButton.text() == self._STOP: self.stortPushButton.setText(self._START)
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)
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'))
class BottomButtons(QFrame): def __init__(self, parent): super(BottomButtons, self).__init__(parent) self.parent = parent self.isPaused = False self.seconds = 0 self.clockTimer = QBasicTimer() self.clockTimer.start(1000, self) self.initUI(self.parent.gameboard) def initUI(self, gameboard): self.setStyleSheet("QWidget { background: #BCBCBC}") self.setFrameStyle(QFrame.Sunken | QFrame.StyledPanel) self.setFixedSize((gameboard.width - 1)*blockSize, 120) self.grid = QGridLayout() self.setLayout(self.grid) hbox = QHBoxLayout() vbox = QVBoxLayout() towerLabel = QLabel() towerLabel.setPixmap(QPixmap(os.path.join('./Pictures/', "tower.png"))) vbox.addWidget(towerLabel) vbox.addLayout(hbox) self.grid.addLayout(vbox, 0, 0) towers = gameboard.getTowers() i = 0 buttons = 0 # We go through the list of different towers in the map and add buttons for them to the bottom left corner of the screen. while i < len(towers): if towers[i] == "t1": self.musketeerButton = BuyButton(QPixmap(os.path.join('./Pictures/', "musketeer_buybutton.png")), QPixmap(os.path.join('./Pictures/', "musketeer_buybutton_hover.png")), QPixmap(os.path.join('./Pictures/', "musketeer_buybutton_pressed.png")), self) self.musketeerButton.move(buttons*towerButtonSize + 10, 50) self.musketeerButton.clicked.connect(self.musketeerButtonClick) hbox.addWidget(self.musketeerButton) buttons += 1 elif towers[i] == "t2": self.cannonButton = BuyButton(QPixmap(os.path.join('./Pictures/', "cannon_buybutton.png")), QPixmap(os.path.join('./Pictures/', "cannon_buybutton_hovered.png")), QPixmap(os.path.join('./Pictures/', "cannon_buybutton_pressed.png")), self) self.cannonButton.move(buttons*towerButtonSize + 10, 50) self.cannonButton.clicked.connect(self.cannonButtonClick) hbox.addWidget(self.cannonButton) buttons += 1 i += 1 hbox.addStretch() ''' slider2 = QSlider(Qt.Horizontal, self) slider2.setFocusPolicy(Qt.NoFocus) slider2.setSliderPosition(100 - self.parent.gameSpeed) #slider2.setGeometry(210, 140, 100, 20) slider2.valueChanged[int].connect(self.changeGameSpeed) hbox2 = QHBoxLayout() hbox2.addWidget(slider2) hbox2.addStretch() self.grid.addLayout(hbox2, 0, 1) ''' hbox3 = QHBoxLayout() vbox3 = QVBoxLayout() hbox3.addStretch() self.lcd = QLCDNumber(self) vbox3.addStretch() vbox3.addWidget(self.lcd) vbox3.addStretch() self.pauseButton = QPushButton('Pause') self.pauseButton.clicked.connect(self.pauseGame) # I could add a restart button vbox3.addWidget(self.pauseButton) self.grid.addLayout(vbox3, 0,2) self.show() def changeGameSpeed(self, value): self.parent.gameSpeed = 100 - value if not self.isPaused: self.parent.timer.stop() self.parent.timer.start(self.parent._gameSpeed, self.parent) def musketeerButtonClick(self): if self.isPaused == False: if self.parent.gameboard.money > Musketeer().price: self.parent.isTowerSelected = True self.parent.selectedTower = Musketeer() self.statusBarMessage('Musketeer tower selected') else: self.statusBarMessage("You don't have enough money.") else: self.statusBarMessage("The game is paused. You can't build towers.") def cannonButtonClick(self): if self.parent.gameover == False: if self.isPaused == False: if self.parent.gameboard.money > Cannon().price: self.parent.isTowerSelected = True self.parent.selectedTower = Cannon() self.statusBarMessage('Cannon tower selected') else: self.statusBarMessage("You don't have enough money.") else: self.statusBarMessage("The game is paused. You can't build towers.") else: self.statusBarMessage("The game has ended can't build towers.") def pauseGame(self, pressed): if self.parent.gameover == False: if self.isPaused == False: self.statusBarMessage('Game paused') self.pauseButton.setText('Play') self.isPaused = True self.parent.timer.stop() self.clockTimer.stop() else: self.statusBarMessage('') self.pauseButton.setText('Pause') self.isPaused = False self.parent.timer.start(self.parent._gameSpeed, self.parent) self.clockTimer.start(1000, self) else: self.statusBarMessage('The game has ended.') def timerEvent(self, event): self.seconds += 1 self.lcd.display("%.2d:%.2d" % (self.seconds // 60, self.seconds % 60)) def statusBarMessage(self, message): self.parent.statusBar().showMessage(message)
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()))
class DedeNimeur(QMainWindow): def __init__(self): super(DedeNimeur, self).__init__() self.statusBar() self.size, self.height, self.width, self.mines = 30, 10, 10, 10 self.lcd = QLCDNumber() self.lcd.setFixedSize(300, 60) self.board = Board(self.height, self.width, self.mines, self.size) self.timer = QBasicTimer() self.real_timer = QElapsedTimer() vbox = QVBoxLayout() vbox.addWidget(self.lcd) vbox.addWidget(self.board) central = QWidget() central.setLayout(vbox) self.setCentralWidget(central) start = QAction('Start', self) start.setStatusTip('Start') start.setShortcut('Ctrl+N') start.triggered.connect(self.init) exit = QAction('Exit', self) exit.setStatusTip('Exit') exit.setShortcut('Ctrl+Q') exit.triggered.connect(qApp.quit) height = QAction('Height', self) height.setStatusTip('Set board width') height.triggered.connect(self.set_height) width = QAction('Width', self) width.setStatusTip('Set board height') width.triggered.connect(self.set_width) mines = QAction('Mines', self) mines.setStatusTip('Set board mines') mines.triggered.connect(self.set_mines) size = QAction('Size', self) size.setStatusTip('Set button size') size.triggered.connect(self.set_size) toolbar = self.addToolBar('Toolbar') toolbar.addAction(start) toolbar.addAction(width) toolbar.addAction(height) toolbar.addAction(mines) toolbar.addAction(size) toolbar.addAction(exit) self.setWindowTitle(u'DédéNimeur') self.show() def init(self): if self.mines < self.height * self.width: self.board.height = self.height self.board.width = self.width self.board.mines = self.mines self.board.size = self.size self.board.init() else: QMessageBox.question(self, 'NOPE', u"Va falloir spécifier un truc cohérent…", QMessageBox.Ok) def set_height(self): text, ok = QInputDialog.getText(self, 'Settings', 'height') if ok: self.height = int(text) self.init() def set_width(self): text, ok = QInputDialog.getText(self, 'Settings', 'width') if ok: self.width = int(text) self.init() def set_mines(self): text, ok = QInputDialog.getText(self, 'Settings', 'mines') if ok: self.mines = int(text) self.init() def set_size(self): text, ok = QInputDialog.getText(self, 'Settings', 'size') if ok: self.size = int(text) self.init() def start_timers(self): self.timer.start(100, self) self.real_timer.start() self.lcd.display(int(self.real_timer.elapsed() / 1000)) def stop_timers(self): self.timer.stop() return self.real_timer.elapsed() def timerEvent(self, e): self.lcd.display(int(self.real_timer.elapsed() / 1000))
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)
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)