def initTimes(self): # Create the local and elapsed times labels self.counter = 0 self.elapsedTime = QLabel() self.localTime = QLabel() # Base font for colours font = QFont() font.setBold(True) font.setItalic(True) # Center labels, transparent backgrounds, fonts, and colours for x in [self.elapsedTime, self.localTime]: # TODO: Scale times with app resize x.setFixedWidth(100) x.setAlignment(Qt.AlignCenter) x.setFont(font) x.setStyleSheet("color: rgb(255, 255, 255)") # Start the elapsedTime timer timer = QTimer(self) timer.timeout.connect(self.updateTimes) # Call updateTimes first to get the times displayed on startUp self.updateTimes() timer.start(500)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.counter = 0 layout = QVBoxLayout() self.l = QLabel("Start") b = QPushButton("DANGER!") b.pressed.connect(self.oh_no) layout.addWidget(self.l) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.show() self.timer = QTimer() self.timer.setInterval(1000) self.timer.timeout.connect(self.recurring_timer) self.timer.start() def oh_no(self): time.sleep(5) def recurring_timer(self): self.counter += 1 self.l.setText("Count: %d" % self.counter)
def __init__(self, graphicsObject: QGraphicsObject): super().__init__() self._graphicsObject = graphicsObject timer = QTimer(self.GraphicsObject()) timer.timeout.connect(self.Update) timer.start(30)
def __init__(self): super().__init__() StylesheetLoader.RegisterWidget(self) self.setWindowIcon(QIcon("Images/UCIcon.png")) centralLayout = QVBoxLayout() centralWidget = QWidget() centralWidget.setLayout(centralLayout) self.setCentralWidget(centralWidget) self._tabWidget = QTabWidget() centralLayout.addWidget(self._tabWidget) menuBar = MenuBar() self.setMenuBar(menuBar) menuBar.saveProgram.connect( lambda: self._tabWidget.currentWidget().SaveProgram()) menuBar.closeProgram.connect( lambda: self.RequestCloseTab(self._tabWidget.currentIndex())) self._tabWidget.tabCloseRequested.connect(self.RequestCloseTab) self._tabWidget.setTabsClosable(True) timer = QTimer(self) timer.timeout.connect(self.CheckPrograms) timer.start(30)
def __init__(self, programInstance: ProgramInstance, uniqueRun): super().__init__() AppGlobals.Instance().onChipModified.connect(self.UpdateParameterItems) self.editingParameterVisibility = False self.programInstance = programInstance self.uniqueRun = uniqueRun self._programNameWidget = QLabel() layout = QVBoxLayout() self.setLayout(layout) self.runButton = QPushButton("Run") self.runButton.clicked.connect(self.RunProgram) self._stopButton = QPushButton("Stop") self._stopButton.clicked.connect(self.StopProgram) self.parameterItems: List[ProgramParameterItem] = [] self._parametersLayout = QVBoxLayout() layout.addWidget(self._programNameWidget) layout.addLayout(self._parametersLayout) layout.addWidget(self.runButton) layout.addWidget(self._stopButton) timer = QTimer(self) timer.timeout.connect(self.UpdateInstanceView) timer.start(30) self.UpdateInstanceView() self.UpdateParameterItems()
def __init__(self): super(Window, self).__init__() aliasedLabel = self.createLabel("Aliased") antialiasedLabel = self.createLabel("Antialiased") intLabel = self.createLabel("Int") floatLabel = self.createLabel("Float") layout = QGridLayout() layout.addWidget(aliasedLabel, 0, 1) layout.addWidget(antialiasedLabel, 0, 2) layout.addWidget(intLabel, 1, 0) layout.addWidget(floatLabel, 2, 0) timer = QTimer(self) for i in range(2): for j in range(2): w = CircleWidget() w.setAntialiased(j != 0) w.setFloatBased(i != 0) timer.timeout.connect(w.nextAnimationFrame) layout.addWidget(w, i + 1, j + 1) timer.start(100) self.setLayout(layout) self.setWindowTitle("Concentric Circles")
class DirectoryWidget(QToolButton): Sg_double_clicked = Signal(str) def __init__(self): super(DirectoryWidget, self).__init__() self.timer = QTimer() self.timer.setSingleShot(True) self.clicked.connect(self.Sl_check_double_click) self.setAccessibleName('Directory') self.setIcon(QIcon(resource_path("icons/Cartella.png"))) self.setIconSize(QSize(45, 45)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) @Slot() def Sl_check_double_click(self): success = False if self.timer.isActive(): time = self.timer.remainingTime() if time > 0: self.double_clicked_action() success = True self.timer.stop() if time <= 0: self.timer.start(250) if not self.timer.isActive() and not success: self.timer.start(250) def double_clicked_action(self) -> None: pass
class FileWidget(QToolButton): Sg_double_clicked = Signal() def __init__(self, file: File): super(FileWidget, self).__init__() self.timer = QTimer() self.timer.setSingleShot(True) self.clicked.connect(self.check_double_click) self.Sg_double_clicked.connect(self.Sl_on_double_click) self.setAccessibleName('File') self.name = file.get_name() self.creation_date = file.get_creation_date() self.last_modified_date = file.get_last_modified_date() self.extension = self.get_extension() self.set_icon() self.setText(self.name) def get_extension(self) -> str: if self.name.find('.') != -1: e = self.name.split(".") return e[-1] else: return "no" def set_icon(self): self.setIconSize(QSize(45, 45)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) if self.extension in ["txt", "xml", "json", "docx", "xlsx"]: self.setIcon(QIcon(resource_path('icons/Txt.png'))) elif self.extension in ["mp4", "avi", "mpeg", "wmv"]: self.setIcon(QIcon(resource_path('icons/Video.png'))) elif self.extension in ["jpg", "png", "gif"]: self.setIcon(QIcon(resource_path('icons/Immagine.png'))) elif self.extension in ["mp3", "wav", "ogg"]: self.setIcon(QIcon(resource_path('icons/Audio.png'))) else: self.setIcon(QIcon(resource_path('icons/DocGenerico.png'))) def check_double_click(self): if self.timer.isActive(): time = self.timer.remainingTime() if time > 0: self.Sg_double_clicked.emit() self.timer.stop() if time <= 0: self.timer.start(250) if self.timer.isActive() is False: self.timer.start(250) @Slot() def Sl_on_double_click(self): pass
def test_clustering_analyzer(self): dataset = random_dataset(**SIMPLE_PRESET, n_samples=200) main = ClusteringAnalyzer() main.show() main.on_dataset_loaded(dataset) timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(main.save_result) timer.start(2000) app.exec()
def create_progress_bar(self): result = QProgressBar() init_widget(result, "progressBar") result.setRange(0, 10000) result.setValue(0) timer = QTimer(self) timer.timeout.connect(self.advance_progressbar) timer.start(1000) return result
def _create_timer(fn, period: int) -> QTimer: timer = QTimer() def _update_cycle(): timer.stop() fn() timer.start(period) timer.timeout.connect(_update_cycle) timer.start(period) return timer
def __init__(self, dataType: DataType): super().__init__() self.dataType = dataType AppGlobals.Instance().onChipModified.connect(self.Repopulate) self.Repopulate() timer = QTimer(self) timer.timeout.connect(self.UpdateNames) timer.start(30)
class StylesheetLoader: _instance = None @staticmethod def _GetInstance(): if StylesheetLoader._instance is None: StylesheetLoader._instance = StylesheetLoader() return StylesheetLoader._instance @staticmethod def RegisterWidget(widget: QWidget): instance = StylesheetLoader._GetInstance() if instance.stylesheet is None: instance.ReloadSS() instance.widgetsList.append(widget) widget.setStyleSheet(instance.stylesheet) @staticmethod def UnregisterWidget(widget: QWidget): instance = StylesheetLoader._GetInstance() if widget in instance.widgetsList: instance.widgetsList.remove(widget) def __init__(self): self.widgetsList: typing.List[QWidget] = [] self.updateTimer = QTimer(QApplication.topLevelWidgets()[0]) self.updateTimer.timeout.connect(self.TimerUpdate) self.updateTimer.start(1000) self.lastModifiedTime = None self.scriptFilename = "UI/STYLESHEET.css" self.stylesheet = None def TimerUpdate(self): currentModifiedTime = os.path.getmtime(self.scriptFilename) if currentModifiedTime != self.lastModifiedTime: self.ReloadSS() self.lastModifiedTime = currentModifiedTime def ReloadSS(self): f = open(self.scriptFilename) self.stylesheet = f.read() self.widgetsList: typing.List[QWidget] = [ widget for widget in self.widgetsList if widget ] for widget in self.widgetsList: widget.setStyleSheet(self.stylesheet) widget.setStyle(widget.style())
def __init__(self): super().__init__() self.shape1 = None self.x_rot_speed = 1 self.x_shape_rot = 0 self.y_rot_speed = 1 self.y_shape_rot = 0 self.z_rot_speed = 0 self.z_shape_rot = 0 timer = QTimer(self) timer.timeout.connect(self.advance) timer.start(20)
class Face_Get(QMainWindow, DesktopUI): def __init__(self): super(Face_Get, self).__init__() self.face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') self.setupUi(self) self.label.setText('摄像头载入中。。。') self.__set_camera() self.pushButton.clicked.connect(self.catch_pic) self.frame = None self.num = 0 self.file_path = Path(__file__).parent / Path('face') self.nm = QNetworkAccessManager(self) self.nm.finished.connect(self.fffff) def __set_camera(self): self.capture = cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.label.width()) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.label.height()) self.timer = QTimer() self.timer.timeout.connect(self.display_pic) self.timer.start(30) def display_pic(self): ret, face = self.capture.read() self.frame = face frame = cv2.flip(cv2.cvtColor(face, cv2.COLOR_RGB2BGR), 1) image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_RGB888) self.label.setPixmap(QPixmap.fromImage(image)) def catch_pic(self): frame_detected = self.face_cascade.detectMultiScale(self.frame, scaleFactor=1.1, minNeighbors=5) try: x, y, w, h = frame_detected[0] except IndexError: self.label_2.setText('没有检测到人脸') else: if not self.file_path.exists(): self.file_path.mkdir() cv2.imwrite(f'{str(self.file_path)}/{self.num}.jpg', self.frame[y:y + h, x:x + w]) self.num += 1 self.label_2.setText(f"第{self.num}张已生成") def network(self): url = QUrl("http://127.0.0.1:8000/excel_get") res = QNetworkRequest(url) self.nm.get(res) def fffff(self, reply): print(reply.readAll())
def __init__(self): super().__init__() AppGlobals.Instance().onChipDataModified.connect(self.UpdateTitle) AppGlobals.Instance().onChipOpened.connect(self.UpdateTitle) AppGlobals.Instance().onChipSaved.connect(self.UpdateTitle) StylesheetLoader.RegisterWidget(self) self.chipEditor = ChipEditor() self.setCentralWidget(self.chipEditor) self.resize(self.screen().size() / 2) self.move(self.screen().size().width() / 2, 0) self.setWindowIcon(QIcon("Images/UCIcon.png")) self._rigViewer = RigViewer() self._editorWindow = ProgramEditorWindow() self._programList = ProgramList(self) self._programList.onProgramEditRequest.connect(self.EditProgram) self._runningProgramsList = RunningProgramsList() self._editorWindow.setVisible(False) menuBar = MenuBar() menuBar.new.connect(self.NewChip) menuBar.open.connect(self.OpenChip) menuBar.save.connect(self.SaveChip) menuBar.saveAs.connect(lambda: self.SaveChip(True)) menuBar.exit.connect(self.close) menuBar.showRigView.connect(self.ShowRigWidget) menuBar.showProgramList.connect(self.ShowProgramList) menuBar.zoomToFit.connect(self.chipEditor.viewer.Recenter) self.updateWorker = ProgramRunnerWorker(self) self.updateWorker.start() killTimer = QTimer(self) killTimer.timeout.connect(self.CheckForKill) killTimer.start(1000) self.setMenuBar(menuBar) self.ShowRigWidget() self.ShowProgramList() self.ShowProgramEditorWindow() self.ShowRunningProgramsList() self._editorWindow.close() AppGlobals.OpenChip(Chip())
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.threadpool = QtCore.QThreadPool() # 初始化线程池 print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) self.counter = 0 layout = QtWidgets.QVBoxLayout() self.l = QtWidgets.QLabel("Start") b = QtWidgets.QPushButton("DANGER!") b.pressed.connect(self.oh_no) layout.addWidget(self.l) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.show() self.timer = QTimer() self.timer.setInterval(1000) self.timer.timeout.connect(self.recurring_timer) self.timer.start() def oh_no(self): worker = Worker(iterations=random.randint(10, 50)) worker.signals.result.connect(self.worker_output) worker.signals.finished.connect(self.worker_complete) worker.signals.error.connect(self.worker_error) self.threadpool.start(worker) def worker_output(self, s): print("RESULT", s) def worker_complete(self): print("THREAD COMPLETE!") def worker_error(self, t): print("ERROR: %s" % t) def recurring_timer(self): self.counter += 1 self.l.setText("Counter: %d" % self.counter)
def slot_save(self) -> None: save_all_databases() # Misuse message dialog as notification https://stackoverflow.com/a/43134238 msgbox = QMessageBox(self) msgbox.setWindowTitle('Save') msgbox.setText('Saved pointers, constraints and annotations.') msgbox.setModal(False) msgbox.show() # Automatically hide dialog after half a second timer = QTimer(self) timer.timeout.connect(msgbox.close) timer.timeout.connect(timer.stop) timer.timeout.connect(timer.deleteLater) timer.start(500)
class EntropyWidget(QWidget): def __init__(self, parent, view, data): super(EntropyWidget, self).__init__(parent) self.view = view self.data = data self.raw_data = data.file.raw self.block_size = (len(self.raw_data) / 4096) + 1 if self.block_size < 1024: self.block_size = 1024 self.width = int(len(self.raw_data) / self.block_size) self.image = QImage(self.width, 1, QImage.Format_ARGB32) self.image.fill(QColor(0, 0, 0, 0)) self.thread = EntropyThread(self.raw_data, self.image, self.block_size) self.started = False self.timer = QTimer() self.timer.timeout.connect(self.timerEvent) self.timer.setInterval(100) self.timer.setSingleShot(False) self.timer.start() self.setMinimumHeight(UIContext.getScaledWindowSize(32, 32).height()) def paintEvent(self, event): p = QPainter(self) p.drawImage(self.rect(), self.image) p.drawRect(self.rect()) def sizeHint(self): return QSize(640, 32) def timerEvent(self): if not self.started: self.thread.start() self.started = True if self.thread.updated: self.thread.updated = False self.update() def mousePressEvent(self, event): if event.button() != Qt.LeftButton: return frac = float(event.x()) / self.rect().width() offset = int(frac * self.width * self.block_size) self.view.navigateToFileOffset(offset)
class Backend(QObject): updated = Signal(str, arguments=['time']) def __init__(self): super().__init__() # Define timer. self.timer = QTimer() self.timer.setInterval(100) # msecs 100 = 1/10th sec self.timer.timeout.connect(self.update_time) self.timer.start() def update_time(self): # Pass the current time to QML. curr_time = strftime("%H:%M:%S", localtime()) self.updated.emit(curr_time)
def incorrect(self): """Вызывается, если на вопрос был дан неверный ответ.""" global next_question_delay, bad_words, is_auto_next, is_repeat, is_reset_progress, repeats_amount, \ is_smart_offer # Отключение происходит сразу же, чтобы пользователь больше не нажимал # на кнопки с последствиями self.designalize_buttons() # НЕ в режиме повторения добавляем ошибочное слово в список для дальнейшего повторения if not is_repeat: bad_words.append(self.current_word) if is_smart_offer: self.smart_add() # В режиме повторения, если включена опция, сбрасываем прогресс для слова, # если ответ на него неверен elif is_repeat and is_reset_progress: self.word_progress[self.current_repeat_w] = repeats_amount # Меняем стиль виджетов self.ui.l_header.setText("Неправильно!") self.ui.l_header.setObjectName("training-header-incorr") self.ui.l_header.style().unpolish(self.ui.l_header) self.ui.l_header.style().polish(self.ui.l_header) self.ui.progressBar.setObjectName("training-prb-incorr") self.ui.progressBar.style().unpolish(self.ui.progressBar) self.ui.progressBar.style().polish(self.ui.progressBar) # Показываем правильный ответ self.show_correct() self.update_stats() # Аналогично, как и в correct() if is_auto_next: # Создаём таймер, по истечению которого перейдём к следующему вопросу. a_timer = QTimer() a_timer.singleShot(next_question_delay, self.next_question) a_timer.start() else: self.ui.pb_next.show()
def __init__(self, clipboard): QWidget.__init__(self) self.mouse_pos = None self.layout = QVBoxLayout() self.top_bar = TopBar() self.layout.addWidget(self.top_bar) self.view = ModeBasedListView(clipboard) self.layout.addWidget(self.view) self.setLayout(self.layout) self.refresh() timer = QTimer(self) timer.timeout.connect(self.refresh) timer.start(500)
class ImageViewerModel(QObject): image_url_changed = Signal(str) def __init__(self, dirname, parent=None): super().__init__(parent) self.__image_url = '' self.__dirname = dirname self.__image_list = [] self.__timer = QTimer(self) self.__timer.setInterval(IMAGE_INTERVAL) self.__timer.timeout.connect(self.on_timeout) @Property(str, notify=image_url_changed) def image_url(self): return self.__image_url @image_url.setter def image_url(self, value): if self.__image_url != value: self.__image_url = value self.image_url_changed.emit(self.__image_url) @Slot() def start_view(self): self.init_image_list() self.random_set_image() self.__timer.start() def init_image_list(self): self.__image_list = [ str(x) for x in Path(self.__dirname).iterdir() if x.is_file() ] def random_set_image(self): if not self.__image_list: return image = random.choice(self.__image_list) self.__image_list.remove(image) self.image_url = f'file:///{path.join(self.__dirname, image).replace(path.sep, "/")}' def on_timeout(self): if not self.__image_list: self.init_image_list() self.random_set_image()
class WinForm(QWidget): def __init__(self, parent=None): super(WinForm, self).__init__(parent) self.setWindowTitle("QTimer demo") self.listFile = QListWidget() self.label = QLabel('显示当前时间') self.startBtn = QPushButton('开始') self.endBtn = QPushButton('结束') layout = QGridLayout(self) # 初始化一个定时器 self.timer = QTimer(self) # showTime()方法 self.timer.timeout.connect(self.showTime) layout.addWidget(self.label, 0, 0, 1, 2) layout.addWidget(self.startBtn, 1, 0) layout.addWidget(self.endBtn, 1, 1) self.startBtn.clicked.connect(self.startTimer) self.endBtn.clicked.connect(self.endTimer) self.setLayout(layout) def showTime(self): # 获取系统现在的时间 time = QDateTime.currentDateTime() # 设置系统时间显示格式 timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd") # 在标签上显示时间 self.label.setText(timeDisplay) def startTimer(self): # 设置计时间隔并启动 self.timer.start(1000) self.startBtn.setEnabled(False) self.endBtn.setEnabled(True) def endTimer(self): self.timer.stop() self.startBtn.setEnabled(True) self.endBtn.setEnabled(False)
class TimerQT(TimerBase): def __init__(self, *args, **kwargs): self._timer = QTimer() self._timer.timeout.connect(self._on_timer) TimerBase.__init__(self, *args, **kwargs) def __del__(self): self._timer_stop() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop()
def __init__(self): super().__init__() self.runningProgramsListLayout = QVBoxLayout() self._console = QLabel() self.runningProgramListItems: List[RunningProgramItem] = [] layout = QVBoxLayout() layout.addLayout(self.runningProgramsListLayout) clearButton = QPushButton("Clear") clearButton.clicked.connect( lambda: AppGlobals.ProgramRunner().ClearMessages()) layout.addWidget(clearButton) layout.addWidget(self._console) self.setLayout(layout) timer = QTimer(self) timer.timeout.connect(self.Update) timer.start(30)
def correct(self): """Вызывается, если на вопрос был дан верный ответ.""" # Отключение происходит сразу же, чтобы пользователь больше не нажимал # на кнопки с последствиями self.designalize_buttons() global next_question_delay, is_auto_next, is_repeat, score # Меняем стиль виджетов self.ui.l_header.setText("Правильно!") self.ui.l_header.setObjectName("training-header-corr") self.ui.l_header.style().unpolish(self.ui.l_header) self.ui.l_header.style().polish(self.ui.l_header) self.ui.progressBar.setObjectName("training-prb-corr") self.ui.progressBar.style().unpolish(self.ui.progressBar) self.ui.progressBar.style().polish(self.ui.progressBar) score += 1 self.update_stats() # Показываем правильный ответ self.show_correct() # Если мы в режиме повторения, то меняем прогресс для данного слова if is_repeat: self.word_progress[self.current_repeat_w] -= 1 # Срабатывает, если включена опция автоматического перехода if is_auto_next: # Создаём таймер, по истечению которого перейдём к следующему вопросу. a_timer = QTimer() a_timer.singleShot(next_question_delay, self.next_question) a_timer.start() # Иначе демонстрируем кнопку else: self.ui.pb_next.show()
def __init__(self, number, polarity): super().__init__() layout = QVBoxLayout() self.setLayout(layout) self._solenoidButton = QToolButton() self._solenoidButton.setCheckable(True) self._solenoidButton.clicked.connect(self.solenoidClicked.emit) self._polarityButton = QToolButton() self._polarityButton.clicked.connect(self.polarityClicked.emit) layout.addWidget(self._solenoidButton) layout.addWidget(self._polarityButton) self.Update(number, polarity) timer = QTimer(self) timer.timeout.connect(self.UpdateValveState) timer.start(30) self._number = number
def __init__(self, parent, programInstance: ProgramInstance, listWidget): super().__init__(parent) self._programInstance = programInstance self.listWidget = listWidget container = QWidget() self.setAutoFillBackground(True) clayout = QVBoxLayout() self.setLayout(clayout) self.layout().addWidget(container) self._editButton = QPushButton("Edit") self._editButton.clicked.connect( lambda: self.onEdit.emit(self._programInstance.program)) self._deleteButton = QPushButton("Delete") self._deleteButton.clicked.connect( lambda: self.onDelete.emit(self._programInstance.program)) layout = QVBoxLayout() container.setLayout(layout) QApplication.instance().installEventFilter(self) self._instanceWidget = ProgramInstanceWidget(programInstance, False) layout.addWidget(self._instanceWidget) layout.addWidget(self._editButton) layout.addWidget(self._deleteButton) self.setFocusPolicy(Qt.ClickFocus) timer = QTimer(self) timer.timeout.connect(self.Reposition) timer.start(30) self.Reposition() self.show() self.raise_()
class RenderWindow(QWindow): def __init__(self, format): super(RenderWindow, self).__init__() self.setSurfaceType(QWindow.OpenGLSurface) self.setFormat(format) self.context = QOpenGLContext(self) self.context.setFormat(self.requestedFormat()) if not self.context.create(): raise Exception("Unable to create GL context") self.program = None self.timer = None self.angle = 0 def initGl(self): self.program = QOpenGLShaderProgram(self) self.vao = QOpenGLVertexArrayObject() self.vbo = QOpenGLBuffer() format = self.context.format() useNewStyleShader = format.profile() == QSurfaceFormat.CoreProfile # Try to handle 3.0 & 3.1 that do not have the core/compatibility profile # concept 3.2+ has. This may still fail since version 150 (3.2) is # specified in the sources but it's worth a try. if (format.renderableType() == QSurfaceFormat.OpenGL and format.majorVersion() == 3 and format.minorVersion() <= 1): useNewStyleShader = not format.testOption( QSurfaceFormat.DeprecatedFunctions) vertexShader = vertexShaderSource if useNewStyleShader else vertexShaderSource110 fragmentShader = fragmentShaderSource if useNewStyleShader else fragmentShaderSource110 if not self.program.addShaderFromSourceCode(QOpenGLShader.Vertex, vertexShader): raise Exception("Vertex shader could not be added: {} ({})".format( self.program.log(), vertexShader)) if not self.program.addShaderFromSourceCode(QOpenGLShader.Fragment, fragmentShader): raise Exception( "Fragment shader could not be added: {} ({})".format( self.program.log(), fragmentShader)) if not self.program.link(): raise Exception("Could not link shaders: {}".format( self.program.log())) self.posAttr = self.program.attributeLocation("posAttr") self.colAttr = self.program.attributeLocation("colAttr") self.matrixUniform = self.program.uniformLocation("matrix") self.vbo.create() self.vbo.bind() self.verticesData = vertices.tobytes() self.colorsData = colors.tobytes() verticesSize = 4 * vertices.size colorsSize = 4 * colors.size self.vbo.allocate(VoidPtr(self.verticesData), verticesSize + colorsSize) self.vbo.write(verticesSize, VoidPtr(self.colorsData), colorsSize) self.vbo.release() vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) if self.vao.isCreated(): # have VAO support, use it self.setupVertexAttribs() def setupVertexAttribs(self): self.vbo.bind() self.program.setAttributeBuffer(self.posAttr, GL.GL_FLOAT, 0, 2) self.program.setAttributeBuffer(self.colAttr, GL.GL_FLOAT, 4 * vertices.size, 3) self.program.enableAttributeArray(self.posAttr) self.program.enableAttributeArray(self.colAttr) self.vbo.release() def exposeEvent(self, event): if self.isExposed(): self.render() if self.timer is None: self.timer = QTimer(self) self.timer.timeout.connect(self.slotTimer) if not self.timer.isActive(): self.timer.start(10) else: if self.timer and self.timer.isActive(): self.timer.stop() def render(self): if not self.context.makeCurrent(self): raise Exception("makeCurrent() failed") functions = self.context.functions() if self.program is None: functions.glEnable(GL.GL_DEPTH_TEST) functions.glClearColor(0, 0, 0, 1) self.initGl() retinaScale = self.devicePixelRatio() functions.glViewport(0, 0, self.width() * retinaScale, self.height() * retinaScale) functions.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) self.program.bind() matrix = QMatrix4x4() matrix.perspective(60, 4 / 3, 0.1, 100) matrix.translate(0, 0, -2) matrix.rotate(self.angle, 0, 1, 0) self.program.setUniformValue(self.matrixUniform, matrix) if self.vao.isCreated(): self.vao.bind() else: # no VAO support, set the vertex attribute arrays now self.setupVertexAttribs() functions.glDrawArrays(GL.GL_TRIANGLES, 0, 3) self.vao.release() self.program.release() # swapInterval is 1 by default which means that swapBuffers() will (hopefully) block # and wait for vsync. self.context.swapBuffers(self) self.context.doneCurrent() def slotTimer(self): self.render() self.angle += 1 def glInfo(self): if not self.context.makeCurrent(self): raise Exception("makeCurrent() failed") functions = self.context.functions() text = """Vendor: {}\nRenderer: {}\nVersion: {}\nShading language: {} \nContext Format: {}\n\nSurface Format: {}""".format( functions.glGetString(GL.GL_VENDOR), functions.glGetString(GL.GL_RENDERER), functions.glGetString(GL.GL_VERSION), functions.glGetString(GL.GL_SHADING_LANGUAGE_VERSION), print_surface_format(self.context.format()), print_surface_format(self.format())) self.context.doneCurrent() return text