Python PyQt5.QtWidgets.QGraphicsScene() Examples


Python PyQt5.QtWidgets.QGraphicsScene() Examples

The following are 30 code examples for showing how to use PyQt5.QtWidgets.QGraphicsScene(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

+ Save to library
Example 1
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab10.py View Source Project 7 votesvote down vote up
def __init__(self):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi("window.ui", self)
        self.scene = QGraphicsScene(0, 0, 711, 601)
        self.scene.win = self
        self.view.setScene(self.scene)
        self.image = QImage(710, 600, QImage.Format_Alpha8)
        self.image.fill(black)
        self.pen = QPen(black)
        self.draw.clicked.connect(lambda: draw(self))
        self.dial_x.valueChanged.connect(lambda: draw(self))
        self.dial_y.valueChanged.connect(lambda: draw(self))
        self.dial_z.valueChanged.connect(lambda: draw(self))
        self.funcs.addItem("cos(x) * sin(z)")
        self.funcs.addItem("2 * cos(x * z)")
        self.funcs.addItem("exp(sin(sqrt(x^2 + z^2)))")
        self.funcs.addItem("x^2 / 20 + z^2 / 20")
        self.funcs.addItem("|sin(x) * sin(z)|") 
Example 2
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab4.py View Source Project 6 votesvote down vote up
def __init__(self):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi("window.ui", self)
        self.scene = QtWidgets.QGraphicsScene(0, 0, 511, 511)
        self.mainview.setScene(self.scene)
        self.image = QImage(511, 511, QImage.Format_ARGB32_Premultiplied)
        self.pen = QPen()
        self.color_line = QColor(Qt.black)
        self.color_bground = QColor(Qt.white)
        self.draw_once.clicked.connect(lambda: draw_once(self))
        self.clean_all.clicked.connect(lambda: clear_all(self))
        self.btn_bground.clicked.connect(lambda: get_color_bground(self))
        self.btn_line.clicked.connect(lambda: get_color_line(self))
        self.draw_centr.clicked.connect(lambda: draw_centr(self))
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(self.what)
        layout.addWidget(self.other)
        self.setLayout(layout)
        self.circle.setChecked(True)
        self.canon.setChecked(True)
        #self.circle.toggled.connect(lambda : change_text(self)) 
Example 3
Project: brown   Author: ajyoon   File: app_interface.py View Source Project 6 votesvote down vote up
def __init__(self, document):
        """
        Args:
            document (Document):
        """
        super().__init__(None)  # no brown object exists for this
                                # TODO: make one
        self.document = document
        self.app = QtWidgets.QApplication([])
        self.main_window = MainWindow()
        self.scene = QtWidgets.QGraphicsScene()
        self.view = self.main_window.graphicsView
        self.view.setScene(self.scene)
        self.registered_music_fonts = {}
        self.font_database = QtGui.QFontDatabase()

    ######## PUBLIC METHODS ######## 
Example 4
Project: Laborejo   Author: hilbrichtsoftware   File: structures.py View Source Project 6 votesvote down vote up
def __init__(self, parent):
        super(GuiGrid, self).__init__()
        self.parent = parent #QGraphicsScene

        self.initialGridExists = False
        self.gapVertical = None #gets recalculated if gridRhythm is changed by the user, or through stretching.
        self.gapHorizontal = None #is constant, but for symetry reasons this is put into redrawTickGrid as well

        self.width = None #recalculated in reactToresizeEventOrZoom
        self.height = None #recalculated in reactToresizeEventOrZoom

        self.linesHorizontal = [] #later the grid lines will be stored here
        self.linesVertical = [] #later the grid lines will be stored here

        self.horizontalScrollbarWaitForGapJump = 0
        self.oldHorizontalValue = 0

        self.verticalScrollbarWaitForGapJump = 0
        self.oldVerticalValue = 0

        self.parent.parentView.verticalScrollBar().valueChanged.connect(self.reactToVerticalScroll)
        self.parent.parentView.horizontalScrollBar().valueChanged.connect(self.reactToHorizontalScroll)

        self.setOpacity(constantsAndConfigs.gridOpacity) 
Example 5
Project: urh   Author: jopohl   File: Modulator.py View Source Project 6 votesvote down vote up
def data_scene(self) -> QGraphicsScene:
        ones = np.ones(self.samples_per_bit, dtype=np.float32) * 1
        zeros = np.ones(self.samples_per_bit, dtype=np.float32) * -1
        n = self.samples_per_bit * len(self.display_bits)
        y = []
        for bit in self.display_bits:
            if bit == "0":
                y.extend(zeros)
            elif bit == "1":
                y.extend(ones)
        x = np.arange(0, n).astype(np.int64)
        scene = ZoomableScene()
        scene.setSceneRect(0, -1, n, 2)
        scene.setBackgroundBrush(constants.BGCOLOR)
        scene.addLine(0, 0, n, 0, QPen(constants.AXISCOLOR, Qt.FlatCap))
        y = np.array(y) if len(y) > 0 else np.array(y).astype(np.float32)
        path = path_creator.array_to_QPath(x, y)
        scene.addPath(path, QPen(constants.LINECOLOR, Qt.FlatCap))
        return scene 
Example 6
Project: PyNoder   Author: johnroper100   File: graph_view.py View Source Project 5 votesvote down vote up
def reset(self):
        self.setScene(QtWidgets.QGraphicsScene())

        self.__connections = set()
        self.__nodes = {}
        self.__selection = set()

        self._manipulationMode = 0
        self._selectionRect = None 
Example 7
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab3.py View Source Project 5 votesvote down vote up
def __init__(self):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi("window.ui", self)
        self.scene = QtWidgets.QGraphicsScene(0, 0, 511, 511)
        self.mainview.setScene(self.scene)
        self.image = QImage(511, 511, QImage.Format_ARGB32_Premultiplied)
        self.pen = QPen()
        self.color_line = QColor(Qt.black)
        self.color_bground = QColor(Qt.white)
        self.draw_line.clicked.connect(lambda: draw_line(self))
        self.clean_all.clicked.connect(lambda : clear_all(self))
        self.btn_bground.clicked.connect(lambda: get_color_bground(self))
        self.btn_line.clicked.connect(lambda: get_color_line(self))
        self.draw_sun.clicked.connect(lambda: draw_sun(self))
        self.cda.setChecked(True) 
Example 8
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab3.py View Source Project 5 votesvote down vote up
def get_color_bground(win):
    color = QtWidgets.QColorDialog.getColor(initial=Qt.white, title='???? ????',
                                            options=QtWidgets.QColorDialog.DontUseNativeDialog)
    if color.isValid():
        win.color_bground = color
        win.image.fill(color)
        s = QtWidgets.QGraphicsScene(0, 0, 10, 10)
        s.setBackgroundBrush(color)
        win.bground_color.setScene(s)
        win.scene.setBackgroundBrush(color) 
Example 9
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab3.py View Source Project 5 votesvote down vote up
def get_color_line(win):
    color = QtWidgets.QColorDialog.getColor(initial=Qt.black, title='???? ?????',
                                            options=QtWidgets.QColorDialog.DontUseNativeDialog)
    if color.isValid():
        win.color_line = color
        win.pen.setColor(color)
        s = QtWidgets.QGraphicsScene(0, 0, 10, 10)
        s.setBackgroundBrush(color)
        win.line_color.setScene(s) 
Example 10
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab4.py View Source Project 5 votesvote down vote up
def get_color_line(win):
    color = QtWidgets.QColorDialog.getColor(initial=Qt.black, title='???? ?????',
                                            options=QtWidgets.QColorDialog.DontUseNativeDialog)
    if color.isValid():
        win.color_line = color
        win.pen.setColor(color)
        s = QtWidgets.QGraphicsScene(0, 0, 10, 10)
        s.setBackgroundBrush(color)
        win.line_color.setScene(s) 
Example 11
Project: axopy   Author: ucdrascal   File: canvas.py View Source Project 5 votesvote down vote up
def _init_scene(self):
        scene = QtWidgets.QGraphicsScene()
        scene.setSceneRect(*self.rect)

        self.setScene(scene)
        self.setRenderHint(QtGui.QPainter.Antialiasing)

        self.setBackgroundBrush(QtGui.QColor(self.bg_color)) 
Example 12
Project: AntScheduler   Author: mcalus3   File: UIController.py View Source Project 5 votesvote down vote up
def graph_create(self):
        graph_text = self.OperationList.toPlainText()
        self.nodes_list = Graph.graph_create(graph_text)

        # draw a graph image
        ImagesApi.draw_graph(self.nodes_list)
        svg_item = QtSvg.QGraphicsSvgItem(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', "ProcessGraph.gv.svg"))
        scene = QtWidgets.QGraphicsScene()
        scene.addItem(svg_item)
        self.processView.setScene(scene) 
Example 13
Project: vivisect-py3   Author: bat-serjo   File: funcgraph.py View Source Project 5 votesvote down vote up
def __init__(self, *args, **kwargs):
        QtWidgets.QGraphicsScene.__init__(self, *args, **kwargs)
        try:
            e_qt_memory.EnviNavMixin.__init__(self)
        except Exception:
            pass 
Example 14
Project: vivisect-py3   Author: bat-serjo   File: qgraphtree.py View Source Project 5 votesvote down vote up
def __init__(self, vg, nodes, parent=None):
        QtWidgets.QGraphicsView.__init__(self, parent=parent)
        scene = QtWidgets.QGraphicsScene(parent=self)

        self.setScene(scene)
        self._v_nodecol = NodeColumn(vg, nodes, scene)
        self._v_vg = vg 
Example 15
Project: vivisect-py3   Author: bat-serjo   File: qtrend.py View Source Project 5 votesvote down vote up
def __init__(self, graph, parent=None):
        QtWidgets.QGraphicsView.__init__(self, parent=parent)
        vg_render.GraphRenderer.__init__(self, graph)

        scene = QtWidgets.QGraphicsScene(parent=self)
        self.setScene(scene) 
Example 16
Project: pyqt5   Author: yurisnm   File: SimpleFreeHand.py View Source Project 5 votesvote down vote up
def __init__(self):
        super(GraphicsView, self).__init__()
        self.setScene(QGraphicsScene())
        self.path = QPainterPath()
        self.item = GraphicsPathItem()
        self.scene().addItem(self.item) 
Example 17
Project: defconQt   Author: trufont   File: drawing.py View Source Project 5 votesvote down vote up
def applyEffectToPixmap(pixmap, effect):
    scene = QGraphicsScene()
    item = QGraphicsPixmapItem()
    item.setPixmap(pixmap)
    item.setGraphicsEffect(effect)
    scene.addItem(item)
    res = QPixmap(pixmap.size())
    res.fill(Qt.transparent)
    painter = QPainter(res)
    scene.render(painter)
    return res 
Example 18
Project: mindfulness-at-the-computer   Author: SunyataZero   File: breathing_history_wt.py View Source Project 5 votesvote down vote up
def __init__(self):
        super().__init__()
        self.show()
        self.setMinimumHeight(300)
        self.setMinimumWidth(270)

        self.ib_qtimer = None
        self.ob_qtimer = None
        self.updating_gui_bool = False
        # self.breathing_rest_counter_int = 0
        # self.breath_counter_int = 0
        self.new_cycle_bool = True

        self.in_breath_graphics_qgri_list = []
        self.out_breath_graphics_qgri_list = []

        vbox_l2 = QtWidgets.QVBoxLayout()
        self.setLayout(vbox_l2)

        self.breathing_graphicsview = QtWidgets.QGraphicsView()  # QGraphicsScene
        vbox_l2.addWidget(self.breathing_graphicsview)
        self.breathing_graphicsscene = QtWidgets.QGraphicsScene()
        self.breathing_graphicsview.setScene(self.breathing_graphicsscene)
        # self.breathing_graphicsview.centerOn(QtCore.Qt.AlignRight)
        # alignment can be set with "setAlignment"
        self.breathing_graphicsview.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag) 
Example 19
Project: mindfulness-at-the-computer   Author: SunyataZero   File: breathing_popup.py View Source Project 5 votesvote down vote up
def __init__(self):
        super().__init__()

        self.view_width_int = 330
        self.view_height_int = 160
        self.setFixedWidth(self.view_width_int)
        self.setFixedHeight(self.view_height_int)
        t_brush = QtGui.QBrush(QtGui.QColor(20, 100, 10))
        self.setBackgroundBrush(t_brush)
        self.setRenderHints(
            QtGui.QPainter.Antialiasing |
            QtGui.QPainter.SmoothPixmapTransform
        )
        self.setAlignment(QtCore.Qt.AlignCenter)

        self.graphics_scene = QtWidgets.QGraphicsScene()
        self.setScene(self.graphics_scene)

        # Custom dynamic breathing graphic
        self.custom_gi = BreathingGraphicsObject()
        self.graphics_scene.addItem(self.custom_gi)
        self.custom_gi.update_pos_and_origin_point(self.view_width_int, self.view_height_int)
        self.custom_gi.enter_signal.connect(self.ib_start)
        self.custom_gi.leave_signal.connect(self.ob_start)

        # Text
        self.text_gi = TextGraphicsItem()
        self.graphics_scene.addItem(self.text_gi)
        self.text_gi.setAcceptHoverEvents(False)
        # -so that the underlying item will not be disturbed
        ib_str = mc.model.PhrasesM.get(mc.mc_global.active_phrase_id_it).ib_str
        # self.text_gi.setPlainText(ib_str)
        self.text_gi.setHtml(mc.mc_global.get_html(ib_str))
        self.text_gi.setTextWidth(200)
        self.text_gi.update_pos_and_origin_point(self.view_width_int, self.view_height_int)
        self.text_gi.setDefaultTextColor(QtGui.QColor(200, 190, 10))

        self.peak_scale_ft = 1 
Example 20
Project: urh   Author: jopohl   File: live_spectrogram.py View Source Project 5 votesvote down vote up
def go():
    global graphic_view, status_label
    data_parent, data_child = Pipe(duplex=False)
    receiver = Process(target=generate_data, args=(data_child,))
    receiver.daemon = True
    receiver.start()

    scene = QGraphicsScene()
    graphic_view.setScene(scene)
    scene.setSceneRect(0, 0, 1024, 1024)

    x_pos = 0
    y_pos = 0
    t = time.time()
    while True:
        speed = time.time()
        data = data_parent.recv()
        spectrogram = Spectrogram(data)
        pixmap = QPixmap.fromImage(spectrogram.create_spectrogram_image(transpose=True))

        scene.setSceneRect(scene.sceneRect().adjusted(0, 0, 0, pixmap.height()))
        item = scene.addPixmap(pixmap)
        item.setPos(x_pos, y_pos)
        y_pos += pixmap.height()
        graphic_view.fitInView(scene.sceneRect())
        status_label.setText("Height: {0:.0f} // Speed: {1:.2f}  // Total Time: {2:.2f}".format(scene.sceneRect().height(),
                                                                                                1/(time.time()-speed),
                                                                                                time.time()-t))
        QApplication.instance().processEvents() 
Example 21
Project: urh   Author: jopohl   File: SpectrumDialogController.py View Source Project 5 votesvote down vote up
def __init__(self, project_manager, parent=None, testing_mode=False):
        super().__init__(project_manager, is_tx=False, parent=parent, testing_mode=testing_mode)

        self.graphics_view = self.ui.graphicsViewFFT
        self.update_interval = 1
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_spectrum)
        self.hide_receive_ui_items()
        self.hide_send_ui_items()

        self.setWindowTitle("Spectrum Analyzer")
        self.setWindowIcon(QIcon(":/icons/icons/spectrum.svg"))
        self.ui.btnStart.setToolTip(self.tr("Start"))
        self.ui.btnStop.setToolTip(self.tr("Stop"))

        self.scene_manager = FFTSceneManager(parent=self, graphic_view=self.graphics_view)

        self.graphics_view.setScene(self.scene_manager.scene)
        self.graphics_view.scene_manager = self.scene_manager

        self.ui.graphicsViewSpectrogram.setScene(QGraphicsScene())
        self.__clear_spectrogram()

        self.init_device()
        self.set_bandwidth_status()

        self.gain_timer = QTimer()
        self.gain_timer.setSingleShot(True)
        self.gain_timer.timeout.connect(self.ui.spinBoxGain.editingFinished.emit)

        self.if_gain_timer = QTimer()
        self.if_gain_timer.setSingleShot(True)
        self.if_gain_timer.timeout.connect(self.ui.spinBoxIFGain.editingFinished.emit)

        self.bb_gain_timer = QTimer()
        self.bb_gain_timer.setSingleShot(True)
        self.bb_gain_timer.timeout.connect(self.ui.spinBoxBasebandGain.editingFinished.emit)

        self.create_connects() 
Example 22
Project: songscreen   Author: maccesch   File: song_text_widget.py View Source Project 5 votesvote down vote up
def __init__(self, *args, **kwargs):
        super(SongTextWidget, self).__init__(*args, **kwargs)

        self.setWindowTitle(self.tr("Lyrics"))

        self.w = 1920
        self.h = 1080

        self._progress = 0.0
        # self._animated_progress = 0.0

        self.title = ""

        self._linecount = 0
        self._extra_lines_after = []
        self._first_lyrics_line_y = 0

        self._covered = True

        self.setMinimumHeight(9 * 50)
        self.setMinimumWidth(16 * 50)

        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)

        self.setScene(QGraphicsScene(self))
        self.setRenderHints(QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform)
        self.setInteractive(False)
        self.scene().setBackgroundBrush(Qt.black)
        self.setStyleSheet( "QGraphicsView { border-style: none; }" )

        self._line_height = 10
        self._document_height = 10

        self._animation = None

        self._font_size = 40
        self._line_increment = 2 
Example 23
Project: SantosGUI   Author: santosfamilyfoundation   File: homography.py View Source Project 5 votesvote down vote up
def __init__(self, parent):
        super(HomographyResultView, self).__init__(parent)
        self.cursor_default = QtGui.QCursor(Qt.CrossCursor)
        self.image_loaded = False

        new_scene = QtWidgets.QGraphicsScene(self)
        new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(124, 124, 124)))
        txt = QtWidgets.QGraphicsSimpleTextItem("Compute homography to see results here.")
        new_scene.addItem(txt)
        self.setScene(new_scene)
        self.show() 
Example 24
Project: SantosGUI   Author: santosfamilyfoundation   File: homography.py View Source Project 5 votesvote down vote up
def load_image(self, image):
        """
        Call this to load a new image from the provide QImage into
        this HomographyView's scene. The image's top left corner will
        be placed at (0,0) in the scene.
        """
        self.scene_image = image
        new_scene = QtWidgets.QGraphicsScene(self)
        pmap = QtGui.QPixmap().fromImage(image)
        pmapitem = new_scene.addPixmap(pmap)
        new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))
        self.setScene(new_scene)
        self.fitInView(0, 0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
        self.show()
        self.image_loaded = True 
Example 25
Project: SantosGUI   Author: santosfamilyfoundation   File: homography.py View Source Project 5 votesvote down vote up
def clear_image(self):
        """
        Call this to clear the image from this HomographyView's scene.
        The scene will be filled with a placeholder grey background and message.
        """
        new_scene = QtWidgets.QGraphicsScene(self)
        new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(124, 124, 124)))
        txt = QtWidgets.QGraphicsSimpleTextItem("Compute homography to see results here.")
        new_scene.addItem(txt)
        self.setScene(new_scene)
        self.show() 
Example 26
Project: echolocation   Author: hgross   File: radar.py View Source Project 4 votesvote down vote up
def __init__(self, parent=None):
        super().__init__(parent)

        width, height = 800, 800
        self.setGeometry(width, height, width, height)

        # configs, can be changed at runtime
        self.circle_line_color = Qt.gray
        self.crosshair_line_color = Qt.gray
        self.text_label_color = Qt.darkGreen
        self.measured_distances_color = Qt.green
        self.circle_count = 10
        self.dot_width = 10
        self.line_width = 1
        self.distance_measurement_angle = 15
        self.measurement_angle = 10  # degrees that one sensor covers
        self.fade_out_time = 4  # older measurements will fade out over this time
        self.add_text_labels = False

        # data
        self.measurements = []
        self.added_time = dict()  # measurement -> timestamp

        # drawing timer
        self.timer = QTimer()
        self.timer.setInterval(80)
        self.timer.timeout.connect(self.draw_radar)
        self.timer.start()

        # internal canvas setup
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.scene = QGraphicsScene()
        self.scene.setSceneRect(0, 0, width, height)
        self.canvas = QGraphicsView()
        self.canvas.setRenderHint(QPainter.Antialiasing)
        self.canvas.setFixedSize(width, height)
        self.canvas.setAlignment(Qt.AlignLeft)
        self.canvas.setScene(self.scene)
        self.canvas.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.canvas.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.layout.addWidget(self.canvas)

        # initial rendering
        self.draw_radar() 
Example 27
Project: git-annex-metadata-gui   Author: alpernebbi   File: file_preview.py View Source Project 4 votesvote down vote up
def preview_image_file(self, path):
        filename = path.split('/')[-1]

        if self.graphics_preview is None:
            msg = "Graphics preview widget not created yet."
            logger.critical(msg)
            return

        if not self.isVisible():
            msg = "Preview widget invisible, not previewing image."
            logger.info(msg)
            return

        self.setCurrentWidget(self.graphics_preview)

        scene = QtWidgets.QGraphicsScene(self)
        self.graphics_preview.setScene(scene)

        # Using QImage instead of directly creating the QPixmap
        # prevents a segmentation fault in my container setup
        image = QtGui.QImage(path)
        if image.isNull():
            fmt = "File '{}' should be an image, but isn't."
            msg = fmt.format(filename)
            logger.error(msg)
            return

        pixmap = QtGui.QPixmap.fromImage(image)
        if pixmap.isNull():
            fmt = "Failed to generate pixmap from image '{}'."
            msg = fmt.format(filename)
            logger.critical(msg)
            return

        pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
        scene.addItem(pixmap_item)
        self.graphics_preview.fitInView(
            pixmap_item,
            Qt.Qt.KeepAspectRatio,
        )

        fmt = "Previewed file '{}' as an image."
        msg = fmt.format(filename)
        logger.info(msg) 
Example 28
Project: plexdesktop   Author: coryo   File: photo_viewer.py View Source Project 4 votesvote down vote up
def __init__(self, name, parent=None):
        super().__init__(name, parent)
        self.ui = plexdesktop.ui.photo_viewer_ui.Ui_PhotoViewer()
        self.ui.setupUi(self)

        self.scene = QtWidgets.QGraphicsScene(self)
        self.ui.view.setScene(self.scene)
        self.resize(self.sizeHint())

        self.pixmap = QtGui.QPixmap()
        self.pixmap_item = QtWidgets.QGraphicsPixmapItem()
        self.draw_timer = QtCore.QTimer()
        self.draw_timer.setSingleShot(True)
        self.draw_timer.setInterval(200)
        self.draw_timer.timeout.connect(self.scale_pixmap)

        self.worker_thread = QtCore.QThread(self)
        self.worker_thread.start()
        self.worker = plexdesktop.workers.ImageWorker()
        self.worker.signal.connect(self.update_img)
        self.worker.moveToThread(self.worker_thread)
        self.operate.connect(self.worker.run)
        self.operate.connect(self.show_indicator)
        self.worker.signal.connect(self.hide_indicator)
        self.worker_thread.finished.connect(self.worker_thread.deleteLater)
        self.worker_thread.finished.connect(self.worker.deleteLater)

        self.rotation = 0
        self.drag_position = None

        self.ui.actionBack.triggered.connect(self.prev)
        self.ui.actionForward.triggered.connect(self.next)
        self.ui.actionRotateLeft.triggered.connect(self.rotate_ccw)
        self.ui.actionRotateRight.triggered.connect(self.rotate_cw)
        self.ui.actionRefresh.triggered.connect(self.rotate_default)

        style = plexdesktop.style.Style.Instance()
        style.widget.register(self.ui.actionBack, 'glyphicons-chevron-left')
        style.widget.register(self.ui.actionForward, 'glyphicons-chevron-right')
        style.widget.register(self.ui.actionRotateLeft, 'glyphicons-rotate-left')
        style.widget.register(self.ui.actionRotateRight, 'glyphicons-rotate-right')
        style.widget.register(self.ui.actionRefresh, 'glyphicons-refresh')
        style.refresh() 
Example 29
Project: pisi-player   Author: mthnzbk   File: main.py View Source Project 4 votesvote down vote up
def __init__(self, parent=None):
        super().__init__()
        self.resize((settings().value("Player/resize") or QSize(640, 480)))
        self.move((settings().value("Player/position") or QPoint(250, 150)))
        self.setWindowTitle("Pisi Player")
        self.setWindowIcon(QIcon(":/data/images/pisiplayer.svg"))
        self.setStyleSheet("background-color: black; border: none;")
        self.setScene(QGraphicsScene())
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setAcceptDrops(True)

        self.subtitleitem = SubtitleItemText(self)
        self.player = Player(self)


        self.scene().addItem(self.player)
        self.scene().addItem(self.subtitleitem)

        self.bar = Bar(self)
        self.scene().addWidget(self.bar)

        self.player.player.durationChanged.connect(self.bar.videoSliderMax)
        self.player.player.positionChanged.connect(self.bar.videoSliderValue)

        self.player.player.mutedChanged.connect(self.bar.mutedChange)
        self.player.player.stateChanged.connect(self.bar.playingState)
        self.player.player.volumeChanged.connect(self.bar.volumeSlider)

        self.bar.play_and_pause_button.clicked.connect(self.playOrPause)
        self.bar.sound_button.clicked.connect(self.player.mutedState)
        self.bar.sound_volume_slider.valueChanged.connect(self.player.setVolume)

        self.bar.video_slider.sliderMoved.connect(self.player.sliderChanged)

        self.player.subtitlePos.connect(self.subtitleitem.positionValue)
        self.player.isSubtitle.connect(self.bar.cc_button.setVisible)

        self.cursorTimer = QTimer(self)
        self.cursorTimer.timeout.connect(self.mouseAndBarHideOrShow)
        self.cursorTimer.start(3000)

        self.player.playerPlayOrOpen(qApp.arguments())

        self.settings_dialog = SettingsDialog(self)

        self.tube_dialog = TubeDialog(self)

        self.cc_dialog = CCDialog(self)
        self.scene().addWidget(self.cc_dialog)

        self.cc_dialog.subtitleCodecChanged.connect(self.subtitleitem.reParse)
        self.settings_dialog.settingsChanged.connect(self.subtitleitem.settingsChanged) 
Example 30
Project: Laborejo   Author: hilbrichtsoftware   File: structures.py View Source Project 4 votesvote down vote up
def __init__(self, parentView):
        super().__init__()
        self.parentView = parentView
        self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)

        self.tracks = {} #trackId:guiTrack, #if we don't save the instances here in Python space Qt will loose them and they will not be displayed without any error message.

        self.deleteOnIdleStack = [] # a stack that holds hidden items that need to be deleted. Hiding is much faster than deleting so we use that for the blocking function. Since we always recreate items and never re-use this is ok as a list. no need for a set.
        self._deleteOnIdleLoop = QtCore.QTimer()
        self._deleteOnIdleLoop.start(0) #0 means "if there is time"
        self._deleteOnIdleLoop.timeout.connect(self._deleteOnIdle) #processes deleteOnIdleStack

        self.duringTrackDragAndDrop = None #switched to a QGraphicsItem (e.g. GuiTrack) while a track is moved around by the mouse
        self.duringBlockDragAndDrop = None #switched to a QGraphicsItem (e.g. GuiTrack) while a block is moved around by the mouse

        self.conductor = Conductor(parentView = self.parentView)
        self.addItem(self.conductor)
        self.conductor.setPos(0, -1 * self.conductor.totalHeight)

        self.yStart = self.conductor.y() - self.conductor.totalHeight/2

        self.hiddenTrackCounter = QtWidgets.QGraphicsSimpleTextItem("") #filled in by self.redraw on callback tracksChanged (loading or toggling visibility of backend tracks)
        self.addItem(self.hiddenTrackCounter)

        self.backColor = QtGui.QColor()
        self.backColor.setNamedColor("#fdfdff")
        self.setBackgroundBrush(self.backColor)

        self.grid = GuiGrid(parent=self)
        self.addItem(self.grid)
        self.grid.setPos(0, -20 * constantsAndConfigs.stafflineGap) #this is more calculation than simply using self.yStart, and might require manual adjustment in the future, but at least it guarantees the grid matches the staffline positions
        self.grid.setZValue(-50)

        self.cachedSceneHeight = 0 #set in self.redraw. Used by updateTrack to set the sceneRect

        #All Cursors
        self.cursor = Cursor()
        self.addItem(self.cursor)
        self.selection = Selection()
        self.addItem(self.selection)
        self.playhead = Playhead(self)
        self.addItem(self.playhead)
        self.playhead.setY(self.yStart)

        #Callbacks
        api.getCallbacksDatabase().tracksChanged.append(self.redraw)
        api.getCallbacksDatabase().updateTrack.append(self.updateTrack)
        api.getCallbacksDatabase().updateBlockTrack.append(self.trackPaintBlockBackgroundColors)

        api.getCallbacksDatabase().updateGraphTrackCC.append(self.updateGraphTrackCC)
        api.getCallbacksDatabase().updateGraphBlockTrack.append(self.updateGraphBlockTrack)
        api.getCallbacksDatabase().graphCCTracksChanged.append(self.syncCCsToBackend) 
<think>好的,用户的问题是关于如何正确导入和使用PyQt5QtWidgets模块。首先,我需要确认用户的环境是否已经正确安装了PyQt5。根据引用[2]和引用[3],用户可能需要先通过pip或conda安装PyQt5。如果安装后出现问题,可以尝试重新安装或者恢复python3.dll文件。 接下来,导入模块的正确方式。根据引用[1]和引用[4],正确的导入语句应该是从PyQt5导入QtWidgets,然后可能需要导入具体的类,比如QApplication、QWidget等。需要注意的是,每个PyQt5的模块需要单独导入,例如QtCore和QtGui可能有不同的功能。 然后,用户可能想知道如何创建一个基本的GUI应用。通常的步骤是创建QApplication实例,然后创建主窗口部件,添加其他控件,最后显示窗口并进入主事件循环。这里需要确保在创建QApplication实例时传入sys.argv参数,如引用[1]中提到的,否则可能会引发错误。 另外,用户可能遇到导入错误,这时候需要检查安装是否正确,或者是否存在环境问题。例如,如果缺少依赖模块如QtChart,可能需要额外安装,如引用[2]所述。此外,引用[5]提到处理多媒体时可能需要额外的解析包,虽然这可能与当前问题无关,但说明PyQt5的不同模块可能有不同的依赖。 最后,用户可能想知道常见的错误和解决方法。比如,如果导入QtWidgets失败,可能需要检查PyQt5的版本或重新安装。同时,确保代码中正确初始化了QApplication,并在主线程中执行GUI操作。 总结下来,回答需要分步骤说明安装、导入、创建应用实例、构建界面以及处理常见错误的方法,并结合引用中的信息提供具体的代码示例和注意事项。</think>### 如何正确导入和使用 PyQt5QtWidgets 模块 #### 1. 安装 PyQt5 首先确保已正确安装 PyQt5 库: ```bash pip install PyQt5 ``` 如果遇到安装问题,可尝试重新安装或通过 conda(若使用 Anaconda 环境): ```bash conda install pyqt ``` 若出现动态链接库错误(如缺少 `python3.dll`),需检查 Python 环境完整性或重新配置[^3]。 --- #### 2. 基础导入方法 在 Python 脚本中导入 `QtWidgets` 模块: ```python from PyQt5 import QtWidgets ``` 若需要使用具体组件(如窗口、按钮),需进一步导入子类: ```python from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton ``` --- #### 3. 创建基础 GUI 应用程序 **步骤说明:** 1. **创建应用实例** PyQt5 要求所有 GUI 程序必须创建 `QApplication` 对象,并传入 `sys.argv` 参数: ```python import sys app = QtWidgets.QApplication(sys.argv) # 必须传入 sys.argv[^1] ``` 2. **构建主窗口** 继承 `QMainWindow` 类定义窗口,并添加控件: ```python class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("示例程序") self.button = QPushButton("点击我", self) self.button.clicked.connect(self.on_click) def on_click(self): print("按钮被点击!") ``` 3. **显示窗口并启动事件循环** ```python window = MainWindow() window.show() sys.exit(app.exec_()) # 进入主循环 ``` --- #### 4. 完整代码示例 ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton class MyWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 200) # 窗口位置和大小 self.btn = QPushButton('测试按钮', self) self.btn.move(100, 50) self.btn.clicked.connect(self.button_clicked) def button_clicked(self): print("按钮功能正常!") if __name__ == '__main__': app = QApplication(sys.argv) window = MyWindow() window.show() sys.exit(app.exec_()) ``` --- #### 5. 常见问题解决 - **导入错误 `No module named 'PyQt5.QtWidgets'`** 检查 PyQt5 是否安装成功,或尝试升级版本: ```bash pip install --upgrade PyQt5 ``` - **程序未响应或窗口不显示** 确保在主线程中调用 `app.exec_()`,且未阻塞事件循环(如长时间循环未使用线程)。 - **控件样式异常** 可设置全局样式表或使用 `QtCore.Qt` 中的样式参数: ```python self.btn.setStyleSheet("QPushButton { background-color: #4CAF50; }") ``` --- §§ 1. 如何在 PyQt5 中实现多窗口切换? 2. PyQt5 的信号与槽机制如何使用? 3. 如何处理 PyQt5 中的界面卡顿问题? [^1]: 引用自 PyQt5 导入 QtWidgets 模块的注意事项 [^2]: 引用自 PyQt5 基础安装和模块功能说明 [^3]: 引用自解决动态库缺失问题的方法
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值