def drawOCRPreview(self): factor = 1.0 img = self.prev[0] old_h = img.height() old_w = img.width() pix = img.scaled( QSize(self.preview.size().width() * factor, self.preview.size().height() * factor), Qt.KeepAspectRatio, Qt.SmoothTransformation) #pix = img.scaled(self.preview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) new_h = pix.height() new_w = pix.width() self.ratio_h = old_h / float(new_h) self.ratio_w = old_w / float(new_w) self.scene = QGraphicsScene() self.scene.addPixmap(pix) #self.scene.addPixmap(img) self.previewRects = [] pen = QPen(Qt.yellow) redpen = QPen(Qt.red) bluepen = QPen(Qt.blue) greenpen = QPen(Qt.green) #for box in self.boxes(): # rect = self.addRect(self.scene, box, ratio_w, ratio_h, pen) # self.previewRects.append(rect) rect = self.addRect(self.scene, self.boxlist[0], self.ratio_w, self.ratio_h, pen) self.previewRects.append(rect) self.previewSetScene(self.scene)
def drawStationName(self): """Draw station name snippet to station_name_img""" res = self.current_result name = res.station.name self.station_name.clear() self.station_name.addItems(name.optional_values) self.station_name.setEditText(name.value) font = QFont() font.setPointSize(11) self.station_name.lineEdit().setFont(font) self.setConfidenceColor(self.station_name, name) img = self.cutImage(res.contrast_station_img, name) processedimage = array2qimage(img) pix = QPixmap() pix.convertFromImage(processedimage) if self.station_name_img.height() < pix.height(): pix = pix.scaled(self.station_name_img.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) self.station_name_img.setScene(scene) self.station_name_img.show()
def __createLayout(self): " Creates the widget layout " totalCalls = self.__stats.total_calls totalPrimitiveCalls = self.__stats.prim_calls # The calls were not induced via recursion totalTime = self.__stats.total_tt txt = "<b>Script:</b> " + self.__script + " " + self.__params.arguments + "<br>" \ "<b>Run at:</b> " + self.__reportTime + "<br>" + \ str( totalCalls ) + " function calls (" + \ str( totalPrimitiveCalls ) + " primitive calls) in " + \ FLOAT_FORMAT % totalTime + " CPU seconds" summary = QLabel(txt) summary.setToolTip(txt) summary.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) summary.setFrameStyle(QFrame.StyledPanel) summary.setAutoFillBackground(True) summaryPalette = summary.palette() summaryBackground = summaryPalette.color(QPalette.Background) summaryBackground.setRgb(min(summaryBackground.red() + 30, 255), min(summaryBackground.green() + 30, 255), min(summaryBackground.blue() + 30, 255)) summaryPalette.setColor(QPalette.Background, summaryBackground) summary.setPalette(summaryPalette) self.__scene = QGraphicsScene() self.__viewer = DiagramWidget() self.__viewer.escapePressed.connect(self.__onESC) vLayout = QVBoxLayout() vLayout.setContentsMargins(0, 0, 0, 0) vLayout.setSpacing(0) vLayout.addWidget(summary) vLayout.addWidget(self.__viewer) self.setLayout(vLayout) return
def search(self): # first set/change the font of the serach box font = self.dlg.search_lineEdit.font() font.setItalic(False) self.dlg.search_lineEdit.setFont(font) # clear description and quicklook self.dlg.textEdit.clear() # make a new emptey scene to show if not self.dlg.graphicsView is None: scene = QGraphicsScene() pic = QPixmap() scene.addItem(QGraphicsPixmapItem(pic)) self.dlg.graphicsView.setScene(scene) self.dlg.graphicsView.show() # function the searches for a string in the datasets name, service type and otganization text = self.dlg.search_lineEdit.text() # convert to lower case and remove greek accents in case of Greek text = text.lower() text = self.removeGreekAccents(text) foundDatasets = [] for dataset in self.datasets: # use lowercase characters and remove greek accents , to make the comparison name = self.removeGreekAccents( dataset.getName(self.language).lower()) source = self.removeGreekAccents( dataset.getSource(self.language).lower()) serviceType = self.removeGreekAccents(dataset.serviceType.lower()) if text in name or text in source or text in serviceType: #QMessageBox.information(None, "DEBUG:", str(type(dataset.getName(self.language)))) foundDatasets.append(dataset) #fill the table with the found datasets self.fill_table(foundDatasets)
def updateLanguage(self): # get the new language language = str(self.dlg.language_comboBox.currentText()) # Change the self.language propertie and change the labe;s if language == "English": self.language = "EN" self.dlg.desc_lbl.setText("Description") self.dlg.preview_lbl.setText("Preview") self.dlg.load_btn.setText("Load") self.dlg.close_btn.setText("Close") self.dlg.search_lbl.setText("Search") self.dlg.info_btn.setText("Info") elif language == "Greek": self.language = "GR" self.dlg.desc_lbl.setText(unicode("Περιγραφή", 'utf-8')) self.dlg.preview_lbl.setText(unicode("Προεπισκόπηση",'utf-8')) self.dlg.load_btn.setText(unicode("Φόρτωση",'utf-8')) self.dlg.close_btn.setText(unicode("Κλείσιμο",'utf-8')) self.dlg.search_lbl.setText(unicode("Αναζήτηση",'utf-8')) self.dlg.info_btn.setText(unicode("Πληροφορίες", 'utf-8')) self.dlg.preview_lbl.setAlignment(Qt.AlignRight) #refill the table self.init_table() # clear description and quicklook self.dlg.textEdit.clear() # clear search box #text = self.dlg.search_lineEdit.setText("") self.init_searchBox() # make a new emptey scene to show if not self.dlg.graphicsView is None: scene = QGraphicsScene() pic = QPixmap() scene.addItem(QGraphicsPixmapItem(pic)) self.dlg.graphicsView.setScene(scene) self.dlg.graphicsView.show()
def read_inputs(self): r = self.dev.read() u = r[1] / 1023.0 * 3.3 self.dev.pwm(1, int(u * 65536.0 / 3.3)) self.ui.labelU.setText('%0.3f V' % u) self.ui.progressU.setValue(1000 * u) self.data.pop(0) self.data.append(u) self.scene = QGraphicsScene() self.scene.addLine(-10, 400 - 0, 610, 400 - 0) self.scene.addLine(0, 400 + 10, 0, 400 - 410) self.scene.addLine(-10, 400 - 50, 10, 400 - 50) self.scene.addLine(-10, 400 - 100, 10, 400 - 100) self.scene.addLine(-10, 400 - 150, 10, 400 - 150) self.scene.addLine(-10, 400 - 200, 10, 400 - 200) self.scene.addLine(-10, 400 - 250, 10, 400 - 250) self.scene.addLine(-10, 400 - 300, 10, 400 - 300) self.scene.addLine(-10, 400 - 350, 10, 400 - 350) self.scene.addLine(-10, 400 - 400, 10, 400 - 400) self.scene.addSimpleText('4.0').moveBy(-40, 0 - 10) self.scene.addSimpleText('3.5').moveBy(-40, 50 - 10) self.scene.addSimpleText('3.0').moveBy(-40, 100 - 10) self.scene.addSimpleText('2.5').moveBy(-40, 150 - 10) self.scene.addSimpleText('2.0').moveBy(-40, 200 - 10) self.scene.addSimpleText('1.5').moveBy(-40, 250 - 10) self.scene.addSimpleText('1.0').moveBy(-40, 300 - 10) self.scene.addSimpleText('0.5').moveBy(-40, 350 - 10) self.scene.addSimpleText('0.0').moveBy(-40, 400 - 10) self.scene.addSimpleText('[U/V]').moveBy(-39, 430 - 10) path = QPainterPath() path.moveTo(0, 400 - self.data[0] * 100) for i in xrange(1, 200): path.lineTo(3 * (i + 1), 400 - self.data[i] * 100) self.scene.addPath(path, QPen(QColor(0, 0, 255), 3)) self.ui.graphU.setScene(self.scene)
def __init__(self, parent=None, signalManager=None): OWWidget.__init__(self, parent, signalManager, "Sieve diagram", True) #self.controlArea.setMinimumWidth(250) #set default settings self.data = None self.attrX = "" self.attrY = "" self.attrCondition = "" self.attrConditionValue = "" self.showLines = 1 self.showCases = 0 self.showInColor = 1 self.attributeSelectionList = None self.stopCalculating = 0 self.canvas = QGraphicsScene() self.canvasView = QGraphicsView(self.canvas, self.mainArea) self.mainArea.layout().addWidget(self.canvasView) self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) #GUI self.attrSelGroup = gui.widgetBox(self.controlArea, box="Shown attributes") self.attrXCombo = gui.comboBox( self.attrSelGroup, self, value="attrX", label="X attribute:", orientation="horizontal", tooltip="Select an attribute to be shown on the X axis", callback=self.updateGraph, sendSelectedValue=1, valueType=str, labelWidth=70) self.attrYCombo = gui.comboBox( self.attrSelGroup, self, value="attrY", label="Y attribute:", orientation="horizontal", tooltip="Select an attribute to be shown on the Y axis", callback=self.updateGraph, sendSelectedValue=1, valueType=str, labelWidth=70) gui.separator(self.controlArea) self.conditionGroup = gui.widgetBox(self.controlArea, box="Condition") self.attrConditionCombo = gui.comboBox( self.conditionGroup, self, value="attrCondition", label="Attribute:", orientation="horizontal", callback=self.updateConditionAttr, sendSelectedValue=1, valueType=str, labelWidth=70) self.attrConditionValueCombo = gui.comboBox(self.conditionGroup, self, value="attrConditionValue", label="Value:", orientation="horizontal", callback=self.updateGraph, sendSelectedValue=1, valueType=str, labelWidth=70) gui.separator(self.controlArea) box2 = gui.widgetBox(self.controlArea, box="Visual settings") gui.checkBox(box2, self, "showLines", "Show lines", callback=self.updateGraph) hbox = gui.widgetBox(box2, orientation="horizontal") gui.checkBox(hbox, self, "showCases", "Show data examples...", callback=self.updateGraph) gui.checkBox(hbox, self, "showInColor", "...in color", callback=self.updateGraph) gui.separator(self.controlArea) # self.optimizationDlg = OWSieveOptimization(self, self.signalManager) # optimizationButtons = gui.widgetBox(self.controlArea, "Dialogs", orientation = "horizontal") # gui.button(optimizationButtons, self, "VizRank", callback = self.optimizationDlg.reshow, debuggingEnabled = 0, tooltip = "Find attribute groups with highest value dependency") gui.rubber(self.controlArea) # self.wdChildDialogs = [self.optimizationDlg] # used when running widget debugging # self.graphButton.clicked.connect(self.saveToFileCanvas) self.icons = gui.attributeIconDict self.resize(800, 550) random.seed()
def btnConfirmClicked(self): # check if PIN code corresponds to PIN code stored in database (use SHA-256 to hash passwords!) cursor = self._mysqldb_connection.cursor() query_str = "select * from tblUser where userID='" + self._rfid + "'" cursor.execute(query_str) if cursor.rowcount != 1: self.lblWrongPINCode.setVisible(True) cursor.close() return # fetch (only) matching row from DB tblUser_row = cursor.fetchone() # hash pin entered by user with salt string from DB pincode_hash = SHA256.new(str(self.lnPINCode.text()) + str(tblUser_row[4])).hexdigest().upper() #print pincode_hash if pincode_hash == tblUser_row[3]: # permit access to user and enable widgets accordingly self.lblWrongPINCode.setVisible(False) self.tabWidget.setTabEnabled(1, True) self.tabWidget.setTabEnabled(2, True) self.tabWidget.setTabEnabled(3, True) self.tabWidget.setTabEnabled(4, True) self.lblAuth.setEnabled(False) self.lblPINCode.setEnabled(False) self.lnPINCode.setEnabled(False) self.btnConfirm.setEnabled(False) self.lblHelloMsg.setVisible(True) self.lblHelloMsg.setText("Welcome back, " + tblUser_row[2] + "!") self.lblRemove.setVisible(True) self.grProfilePicture.setVisible(True) self.grProfilePicture.setEnabled(True) scene = QGraphicsScene() qimg = QtGui.QImage.fromData(tblUser_row[6]) pixmap = QGraphicsPixmapItem(QPixmap.fromImage(qimg), None, scene) self.grProfilePicture.setScene(scene) self.grProfilePicture.fitInView(scene.sceneRect(), Qt.KeepAspectRatio) self.grProfilePicture.setVisible(True) self._encourager.say("Welcome back, " + tblUser_row[2] + "!") self._encourager.show_emotion("happy") ### HARDCODED: display different information depending on user connected ### if self._rfid == "3BEA00008131FE450031C573C0014000900077": self.slNbrBlocks.setValue(3) self.spnNbrRepetitions.setValue(25) self.chkQualitative.setChecked(False) self.chkQuantitative.setChecked(True) self.spnQuantEncRep.setEnabled(True) self.cmbQualiEnc.setEnabled(False) self.spnQuantEncRep.setValue(3) else: self.slNbrBlocks.setValue(2) self.spnNbrRepetitions.setValue(15) self.chkQualitative.setChecked(True) self.chkQuantitative.setChecked(True) self.spnQuantEncRep.setEnabled(True) self.spnQuantEncRep.setValue(2) self.cmbQualiEnc.setEnabled(True) self.cmbQualiEnc.setCurrentIndex(1) #launch_params = ['roslaunch', 'simple_image_cyphering', 'one_node_decryption.launch'] #self._decryption_node = Popen(launch_params) else: self.lblWrongPINCode.setVisible(True) cursor.close()
def __init__(self): super(QTRehaZenterGUI, self).__init__() uic.loadUi(currentdir + '/ui_files/QTRehaZenterGUI.ui', self) # connect to DB and create cursor object to perform queries self._mysqldb_connection = MySQLdb.connect(host=self.mysql_hostname, user=self.mysql_user, passwd=self.mysql_password, db="iot") # initialize custom object loader widget self.defineNewColorWidget = DefineNewColor.UIDefineNewColorWidget(self) # disable camera feed tab on startup (enabled later) self.tabWidget.setTabEnabled(2, False) # load logo images uniLuLogoScene = QGraphicsScene() imagePixmap_unilu = QGraphicsPixmapItem(QPixmap(QImage(currentdir + "/imgs/university_of_luxembourg_logo.png")), None, uniLuLogoScene) self.grUniLuLogo.setScene(uniLuLogoScene) self.grUniLuLogo.fitInView(uniLuLogoScene.sceneRect(), Qt.KeepAspectRatio) luxAILogoScene = QGraphicsScene() imagePixmap_luxai = QGraphicsPixmapItem(QPixmap(QImage(currentdir + "/imgs/luxai_logo.png")), None, luxAILogoScene) self.grLuxAILogo.setScene(luxAILogoScene) self.grLuxAILogo.fitInView(luxAILogoScene.sceneRect(), Qt.KeepAspectRatio) # initialize calibration file selection dialog self.dlgLoadCalibFile = QFileDialog() self.dlgLoadCalibFile.setFileMode(QFileDialog.ExistingFile) self.dlgLoadCalibFile.setFilter("Calibration files (*.clb)") self.dlgLoadCalibFile.setAcceptMode(QFileDialog.AcceptOpen) # initialize color file selection dialog self.dlgLoadColorFile = QFileDialog() self.dlgLoadColorFile.setFileMode(QFileDialog.ExistingFile) self.dlgLoadColorFile.setFilter("Color files (*.clr)") self.dlgLoadColorFile.setAcceptMode(QFileDialog.AcceptOpen) # initialize calibration file save dialog self.dlgSaveCalibFile = QFileDialog() self.dlgSaveCalibFile.setFileMode(QFileDialog.AnyFile) self.dlgSaveCalibFile.setFilter("Calibration files (*.clb)") self.dlgSaveCalibFile.setAcceptMode(QFileDialog.AcceptSave) # initialize rotation exercises warning message box self.msgRotationExercises = QMessageBox() self.msgRotationExercises.setIcon(QMessageBox.Warning) self.msgRotationExercises.setText("Sorry, rotation exercises have not been implemented yet!") self.msgRotationExercises.setInformativeText("Please choose one of the motion exercises instead until rotation exercises become available.") self.msgRotationExercises.setWindowTitle("Rotation exercises warning") self.msgRotationExercises.setStandardButtons(QMessageBox.Ok) # initialize calibration fail message box self.msgErrorWarning = QMessageBox() self.msgErrorWarning.setIcon(QMessageBox.Warning) self.msgErrorWarning.setStandardButtons(QMessageBox.Ok) # initialize list of faces (in string form) self._faces_list = ["sad", "happy", "crying", "neutral", "showing_smile", "surprise", "breathing_exercise", "breathing_exercise_nose", "smile", "happy_blinking", "calming_down", "random emotion"] self.cmbFaces.addItems(self._faces_list) # disable various labels and widgets on startup self.lblPerRepetitions1.setEnabled(False) self.lblPerRepetitions2.setEnabled(False) self.spnQuantEncRep.setEnabled(False) self.cmbQualiEnc.setEnabled(False) self.btnDeleteLine.setEnabled(False) self.spnFixedReps.setEnabled(False) self.spnFrequencyReps.setEnabled(False) self.btnAddLine.setEnabled(False) self.lblAuth.setVisible(False) self.lblPINCode.setVisible(False) self.lnPINCode.setVisible(False) self.btnConfirm.setVisible(False) self.lblHelloMsg.setVisible(False) self.lblRemove.setVisible(False) self.grProfilePicture.setVisible(True) self.tabWidget.setTabEnabled(1, False) self.tabWidget.setTabEnabled(2, False) self.tabWidget.setTabEnabled(3, False) self.tabWidget.setTabEnabled(4, False) self.lblWrongPINCode.setVisible(False) self.grProfilePicture.setVisible(False) # resize table columns to match their text size header = self.tblEmotionalFeedback.horizontalHeader() header.setResizeMode(0, QHeaderView.Stretch) header.setResizeMode(1, QHeaderView.Stretch) header.setResizeMode(2, QHeaderView.Stretch) # initialize ROS publisher topics rospy.init_node("reha_interface", anonymous=True) self._exercise_request_pub = rospy.Publisher("exercise_request", ExerciseRequest, queue_size=1) self._exercise_stop_pub = rospy.Publisher("exercise_stop", Bool, queue_size=1) self._calibration_request_pub = rospy.Publisher("calibration_request", CalibrationRequest, queue_size=1) rospy.Subscriber("exercise_reply", ExerciseReply, self._server_reply_callback) rospy.Subscriber("calibration_reply", CalibrationReply, self._server_reply_callback) rospy.Subscriber("/plain/image_modified/compressed", CompressedImage, self._img_received_callback) rospy.Subscriber("/user_logging/initial_key", String, self._smartcard_detected_callback) #self._decryption_node = None # initialize some other necessary variables self._is_calibrating = False self._is_exercise_running = False self._bridge = CvBridge() # connect functions to widgets self.btnInternalRotationExercise.clicked.connect(self.btnInternalRotationExerciseClicked) self.btnExternalRotationExercise.clicked.connect(self.btnExternalRotationExerciseClicked) self.btnAbductionMotionExercise.clicked.connect(self.btnAbductionMotionExerciseClicked) self.btnFlexionMotionExercise.clicked.connect(self.btnFlexionMotionExerciseClicked) self.btnBegin.clicked.connect(self.btnBeginClicked) self.btnStop.clicked.connect(self.btnStopClicked) self.btnDefineNewColor.clicked.connect(self.openDefineNewColorWidget) self.slNbrBlocks.valueChanged.connect(self.slNbrBlocksValueChanged) self.rdFixed.clicked.connect(self.rdFixedClicked) self.rdFrequency.clicked.connect(self.rdFrequencyClicked) self.btnAddLine.clicked.connect(self.btnAddLineClicked) self.cmbFaces.currentIndexChanged.connect(self.cmbFacesCurrentIndexChanged) self.actionQuit.triggered.connect(self.closeEvent) self.btnDeleteLine.clicked.connect(self.btnDeleteLineClicked) self.tblEmotionalFeedback.itemClicked.connect(self.tblEmotionalFeedbackItemClicked) self.chkQualitative.clicked.connect(self.chkQualitativeClicked) self.chkQuantitative.clicked.connect(self.chkQuantitativeClicked) self.btnLoadColorFile.clicked.connect(self.btnLoadColorFileClicked) self.btnLoadCalibFile.clicked.connect(self.btnLoadCalibFileClicked) self.btnCalibrateNow.clicked.connect(self.btnCalibrateNowClicked) self.robot_finished.connect(robot_finished_triggered) self.img_received.connect(img_received_triggered) self.smartcard_rosmsg_received.connect(smartcard_rosmsg_received_triggered) self.logoff_signal_received.connect(logoff_signal_received_triggered) self.btnConfirm.clicked.connect(self.btnConfirmClicked) self.lnPINCode.textChanged.connect(self.disableErrorLabelOnEdit)
def img_received_triggered(gui, img): scene = QGraphicsScene() pixmap = QGraphicsPixmapItem(QPixmap(img), None, scene) gui.grOriginalImage.setScene(scene) gui.grOriginalImage.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
def initAllGraphicViews(self): for oneKey, oneGraphicView in self.graphicViewsMap.items(): scene = QGraphicsScene() oneGraphicView.setScene(scene) return
def setupUi(self, MainWindow): super(Ui_MRMainWindow, self).setupUi(MainWindow) self._main_window = MainWindow self.listView.set_model(self._moviemodel) self._graphic_scene = QGraphicsScene() self.movieCoverView.setScene(self._graphic_scene) self.draw_toolbar() QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), QtCore.QCoreApplication.instance().quit) QtCore.QObject.connect(self.listView, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.candidates_proposition_menu) QtCore.QObject.connect(self.listView, QtCore.SIGNAL("currentItemChanged(\ QListWidgetItem *,QListWidgetItem *)"), self.load_movie_infos_in_view) QtCore.QObject.connect(self.actionAddFiles, QtCore.SIGNAL("triggered()"), self.add_files) QtCore.QObject.connect(self.actionAddDirectory, QtCore.SIGNAL("triggered()"), self.add_directory) QtCore.QObject.connect(self.actionLaunchRenameAssistant, QtCore.SIGNAL("triggered()"), self.do_compute) QtCore.QObject.connect(self.actionLaunchFromSelection, QtCore.SIGNAL("triggered()"), self.do_compute_from_selection) QtCore.QObject.connect(self.actionSave, QtCore.SIGNAL("triggered()"), self.do_batch_save) QtCore.QObject.connect(self.cancelJobButton, QtCore.SIGNAL("clicked()"), self.canceljob) self.listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.listView.connect(self.listView, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.onContext) QtCore.QObject.connect(self._main_window, QtCore.SIGNAL("progress(int)"), self.update_progress_bar) QtCore.QObject.connect(self._main_window, QtCore.SIGNAL("statusmessage(QString)"), self.update_status_bar) QtCore.QObject.connect(self.listView, QtCore.SIGNAL("dropped"), self.file_dropped)
def __init__(self, dataDir="", parent=None): QWidget.__init__(self, parent) self.renderer = QSvgRenderer(dataDir + "poker.svg") self.scene = QGraphicsScene() self.chat = QGraphicsSimpleTextItem() self.table = QGraphicsSvgItem(dataDir + "poker.svg") self.table.setSharedRenderer(self.renderer) self.table.setElementId("table") self.table.setMatrix(self.renderer.matrixForElement("transform_table")) self.scene.addItem(self.chat) self.scene.addItem(self.table) self.board = [] for i in range(5): card = AnimatedGraphicsSvgItem(dataDir + "svg-cards.svg", self.table) card.setElementId("back") parent = self.renderer.matrixForElement("transform_table") child = self.renderer.matrixForElement("transform_card%i" % i) cardMatrix = child.translate(-parent.dx(), -parent.dy()) card.setMatrix(cardMatrix) #card.setFlag(QGraphicsSvgItem.ItemIsMovable, True) card.scale(0.5, 0.5) card.hide() self.scene.addItem(card) self.board.append(card) self.seats = [] self.names = [] self.moneys = [] self.bets = [] for i in range(10): seat = SeatItem() def seatClickedEvent(seat=i): seatClickedCallback = self.seatClicked seatClickedCallback(seat) seat.event = seatClickedEvent seat.setSharedRenderer(self.renderer) seat.setElementId("seat") seat.setMatrix( self.renderer.matrixForElement("transform_seat%i" % i)) self.scene.addItem(seat) self.seats.append(seat) name = QGraphicsSimpleTextItem(seat) name.setMatrix(self.renderer.matrixForElement("seat_name")) self.scene.addItem(name) self.names.append(name) money = QGraphicsSimpleTextItem(seat) money.setMatrix(self.renderer.matrixForElement("seat_money")) self.scene.addItem(money) self.moneys.append(money) bet = QGraphicsSimpleTextItem() bet.setMatrix(self.renderer.matrixForElement("transform_bet%i" % i)) self.scene.addItem(bet) self.bets.append(bet) self.pots = [] for i in range(9): pot = QGraphicsSimpleTextItem() pot.setMatrix(self.renderer.matrixForElement("transform_pot%i" % i)) self.scene.addItem(pot) self.pots.append(pot) self.view = QGraphicsView(self) self.view.setScene(self.scene) self.view.resize(800, 600) self.fold = ActionItem() self.fold.setText("fold") self.fold.setPos(0, 550) self.scene.addItem(self.fold) self.fold.event = lambda: self.foldClicked() self.check = ActionItem() self.check.setText("check") self.check.setPos(50, 550) self.scene.addItem(self.check) self.check.event = lambda: self.checkClicked() self.call = ActionItem() self.call.setText("call") self.call.setPos(100, 550) self.scene.addItem(self.call) self.call.event = lambda: self.callClicked() self.bet = ActionItem() self.bet.setText("bet") self.bet.setPos(150, 550) self.scene.addItem(self.bet) self.bet.event = lambda: self.betClicked()
start = time.time() path_items = generate_path_items_for_labels(pen_table, labels_img, None) print "generate took {}".format(time.time() - start) # 52 ms edges_item = SegmentationEdgesItem(path_items, pen_table) def assign_random_color(id_pair, buttons): print "handling click: {}".format(id_pair) pen = pen_table[id_pair] if pen: pen = QPen(pen) else: pen = QPen() random_color = QColor(*list(np.random.randint(0, 255, (3, )))) pen.setColor(random_color) pen_table[id_pair] = pen edges_item.edgeClicked.connect(assign_random_color) scene = QGraphicsScene() scene.addItem(edges_item) transform = QTransform() transform.scale(5.0, 5.0) view = QGraphicsView(scene) view.setTransform(transform) view.show() view.raise_() app.exec_()
def Paint(self): scene = QGraphicsScene() hor = self.ui.horizontal.currentIndex() vert = self.ui.vertical.currentIndex() v = {"a": [], "d": [], "c": [], "r": [], "f": []} h = {"a": [], "d": [], "c": [], "r": [], "f": []} for alg in self.algs: projects = [] if hor == 0: projects = sorted(self.stats[alg].values(),key=lambda x: 1.0 / 3.0 * (x["computersload"] + x["storesload"] + x["ramload"])) elif hor == 1: projects = sorted(self.stats[alg].values(),key=lambda x: 0.5*(x["computersload"]+x["ramload"])) elif hor == 2: projects = sorted(self.stats[alg].values(),key=lambda x: x["computersload"]) elif hor == 3: projects = sorted(self.stats[alg].values(),key=lambda x: x["ramload"]) elif hor == 4: projects = sorted(self.stats[alg].values(),key=lambda x: x["storesload"]) if projects == []: return for proj in projects: if vert == 0: v[alg].append(proj["assigned"]) elif vert == 1: v[alg].append(proj["ratio"]) elif vert == 2: v[alg].append(proj["replicas"]) if hor == 0: h[alg].append(1.0 / 3.0 * (proj["computersload"] + proj["storesload"] + proj["ramload"])) elif hor == 1: h[alg].append(0.5 * (proj["computersload"] + proj["ramload"])) elif hor == 2: h[alg].append(proj["computersload"]) elif hor == 3: h[alg].append(proj["ramload"]) elif hor == 4: h[alg].append(proj["storesload"]) maxnum = max([max(v[i]) for i in self.algs] + [1]) scene.addLine(5, 5, 5, 213, QPen(self.settings["axis"])) scene.addLine(2, 210, 210, 210, QPen(self.settings["axis"])) for i in range(10): scene.addLine(5 + (i + 1) * 20, 209, 5 + (i + 1) * 20, 211, QPen(self.settings["axis"])) scene.addLine(4, 210 - (i + 1) * 20, 6, 210 - (i + 1) * 20, QPen(self.settings["axis"])) font = QFont() font.setPointSize(6) t1 = scene.addText(str(0.1*(i + 1)), font) t1.setPos((i + 1) * 20, 212) if int(0.1*maxnum*(i + 1)) != 0: t2 = scene.addText(str(int(0.1*maxnum*(i + 1))), font) t2.setPos(-10, 200 - (i + 1) * 20) legendy = 10 for alg in self.algs: x0 = h[alg][0] y0 = v[alg][0] color = QColor(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) brush = QBrush(color) color = QPen(color) for x,y in zip(h[alg],v[alg]): scene.addLine(5 + x0 * 200, 210 - float(y0)/maxnum * 200, 5 + x * 200, 210 - float(y)/maxnum * 200, color) scene.addLine(5 + x * 200 - 2, 210 - float(y)/maxnum * 200 - 2 , 5 + x * 200 + 2, 210 - float(y)/maxnum * 200 + 2, color) scene.addLine(5 + x * 200 + 2, 210 - float(y)/maxnum * 200 - 2, 5 + x * 200 - 2, 210 - float(y)/maxnum * 200 + 2, color) x0 = x y0 = y scene.addRect(220, legendy, 5, 5, color, brush) t = scene.addText(algnames[alg], font) t.setPos(230, legendy-5) legendy += 10 self.ui.graph.setScene(scene)
def __init__(self, parent=None): QGraphicsView.__init__(self, parent) self.setScene(QGraphicsScene())
def slideshow(): folder = None time = None args = sys.argv[:1] for arg in sys.argv[2:]: if arg.startswith("--"): args.append(arg) continue if not folder: folder = arg continue time = arg if folder is None or time is None: # awwww :) print("""usage: %s ROOT SECONDS ROOT points to the root directory where the images are going to be picked up. SECONDS is the time between images.""" % sys.argv[0]) sys.exit(1) sys.argv = args cursor = Qt.BlankCursor app = QApplication(sys.argv) win = QMainWindow() QApplication.setOverrideCursor(cursor) QApplication.changeOverrideCursor(cursor) scene = QGraphicsScene() view = QGraphicsView(scene, win) view.setFrameShadow(QFrame.Plain) view.setFrameStyle(QFrame.NoFrame) view.show() brush = QBrush(QColor(0, 0, 0)) brush.setStyle(Qt.SolidPattern) view.setBackgroundBrush(brush) runner = MainWindow(view, scene, folder) timer = QTimer(app) timer.timeout.connect(runner.nextImage) timer.start(float(time) * 1000) QTimer.singleShot(200, runner.nextImage) timer2 = QTimer(app) timer2.timeout.connect(runner.updateAlbum) timer2.start(60 * 60 * 1000) win.setCentralWidget(view) win.showFullScreen() tv = TV() app.exec_() tv.stop()
def __init__(self, parent): QGraphicsView.__init__(self, parent) self.setScene(QGraphicsScene()) self.setDragMode(QGraphicsView.ScrollHandDrag)
def cleanSnippet(self, graphicsview): scene = QGraphicsScene() graphicsview.setScene(scene)
def __initializeUi(self): """ This method initializes the Widget ui. """ LOGGER.debug("> Initializing '{0}' ui.".format( self.__class__.__name__)) self.Previous_Image_pushButton.setIcon( QIcon( os.path.join(self.__uiResourcesDirectory, self.__uiPreviousImage))) self.Next_Image_pushButton.setIcon( QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiNextImage))) self.Zoom_In_pushButton.setIcon( QIcon( os.path.join(self.__uiResourcesDirectory, self.__uiZoomInImage))) self.Zoom_Out_pushButton.setIcon( QIcon( os.path.join(self.__uiResourcesDirectory, self.__uiZoomOutImage))) len(self.__paths) <= 1 and self.Navigation_frame.hide() LOGGER.debug("> Initializing graphics View.") self.__graphicsView = QGraphicsView() self.__graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__graphicsView.setTransformationAnchor( QGraphicsView.AnchorUnderMouse) self.__graphicsView.setDragMode(QGraphicsView.ScrollHandDrag) # Reimplementing QGraphicsView wheelEvent method. self.__graphicsView.wheelEvent = self.wheelEvent LOGGER.debug("> Initializing graphics scene.") self.__graphicsScene = QGraphicsScene(self.__graphicsView) self.__graphicsScene.setItemIndexMethod(QGraphicsScene.NoIndex) self.__graphicsScene.setSceneRect( -(float(self.__graphicsSceneWidth)) / 2, -(float(self.__graphicsSceneHeight)) / 2, float(self.__graphicsSceneWidth), float(self.__graphicsSceneHeight)) self.__graphicsView.setScene(self.__graphicsScene) self.__graphicsView.setBackgroundBrush( QBrush(self.__graphicsSceneBackgroundColor)) self.Images_Previewer_frame_gridLayout.addWidget(self.__graphicsView) # Signals / Slots. self.__container.engine.imagesCaches.QImage.contentAdded.connect( self.__engine_imagesCaches_QImage__contentAdded) self.Previous_Image_pushButton.clicked.connect( self.__Previous_Image_pushButton__clicked) self.Next_Image_pushButton.clicked.connect( self.__Next_Image_pushButton__clicked) self.Zoom_Out_pushButton.clicked.connect( self.__Zoom_Out_pushButton__clicked) self.Zoom_In_pushButton.clicked.connect( self.__Zoom_In_pushButton__clicked) self.Zoom_Fit_pushButton.clicked.connect( self.__Zoom_Fit_pushButton__clicked)
def setPreviewImage(self, previewImage): self.grscene = QGraphicsScene() pixmapImage = QPixmap(previewImage) self.grscene.addPixmap(pixmapImage) self.setScene(self.grscene)
def scene(self): scene = QGraphicsScene() scene.addItem(self.background_pixmap_item) scene.addItem(self.head_pixmap_item) return scene
def __init__(self, parent=None): super().__init__(parent) # Output changed flag self._changed = False # Diagram update is in progress self._updating = False # Input update is in progress self._inputUpdate = False # All input tables have the same domain. self.samedomain = True # Input datasets in the order they were 'connected'. self.data = OrderedDict() # Extracted input item sets in the order they were 'connected' self.itemsets = OrderedDict() # GUI box = gui.widgetBox(self.controlArea, "Info") self.info = gui.widgetLabel(box, "No data on input\n") self.identifiersBox = gui.radioButtonsInBox( self.controlArea, self, "useidentifiers", [], box="Data Instance Identifiers", callback=self._on_useidentifiersChanged) self.useequalityButton = gui.appendRadioButton( self.identifiersBox, "Use instance equality") rb = gui.appendRadioButton(self.identifiersBox, "Use identifiers") self.inputsBox = gui.indentedBox(self.identifiersBox, sep=gui.checkButtonOffsetHint(rb)) self.inputsBox.setEnabled(bool(self.useidentifiers)) for i in range(5): box = gui.widgetBox(self.inputsBox, "Data set #%i" % (i + 1), addSpace=False) box.setFlat(True) model = itemmodels.VariableListModel(parent=self) cb = QComboBox() cb.setModel(model) cb.activated[int].connect(self._on_inputAttrActivated) box.setEnabled(False) # Store the combo in the box for later use. box.combo_box = cb box.layout().addWidget(cb) gui.rubber(self.controlArea) box = gui.widgetBox(self.controlArea, "Output") cb = gui.checkBox(box, self, "autocommit", "Commit on any change") b = gui.button(box, self, "Commit", callback=self.commit, default=True) gui.setStopper(self, b, cb, "_changed", callback=self.commit) # Main area view self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.view.setRenderHint(QPainter.Antialiasing) self.view.setBackgroundRole(QPalette.Window) self.view.setFrameStyle(QGraphicsView.StyledPanel) self.mainArea.layout().addWidget(self.view) self.vennwidget = VennDiagram() self.vennwidget.resize(400, 400) self.vennwidget.itemTextEdited.connect(self._on_itemTextEdited) self.scene.selectionChanged.connect(self._on_selectionChanged) self.scene.addItem(self.vennwidget) self.resize(self.controlArea.sizeHint().width() + 550, max(self.controlArea.sizeHint().height(), 550)) self._queue = []
y = mappedParentRect.top( ) + NodeGraphicsItem.LEAFSIZE[1] / 2 elif y > mappedParentRect.bottom( ) - NodeGraphicsItem.LEAFSIZE[1] / 2: y = mappedParentRect.bottom( ) - NodeGraphicsItem.LEAFSIZE[1] / 2 value = QPointF(x, y) elif change == QGraphicsItem.ItemPositionHasChanged: self.model.pos = value if isinstance( value, QPointF) else value.toPointF() return super(NodeGraphicsItem, self).itemChange(change, value) if __name__ == '__main__': from PyQt4.QtGui import QApplication, QGraphicsView, QGraphicsScene from treenode import TreeNode import sys app = QApplication(sys.argv) myview = QGraphicsView() myscene = QGraphicsScene(QRectF(-400, -300, 800, 600)) myview.setScene(myscene) rootnode = TreeNode(0, 'root') parentnode = TreeNode(1, 'grass land', parent=rootnode) leafnode = TreeNode(2, 'grass 1', parent=parentnode) # leafnode2 = TreeNode(3,'earth',parent=parentnode) myscene.addItem(NodeGraphicsItem(parentnode)) myview.show() app.exec_()
def __init__(self, parent=None): super().__init__(parent) self.matrix = None self.items = None self.linkmatrix = None self.root = None self._displayed_root = None self.cutoff_height = 0.0 self._invalidated = False gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"), self, "linkage", items=LINKAGE, callback=self._invalidate_clustering) box = gui.widgetBox(self.controlArea, "Annotation") self.label_cb = gui.comboBox(box, self, "annotation_idx", callback=self._update_labels) self.label_cb.setModel(itemmodels.VariableListModel()) self.label_cb.model()[:] = ["None", "Enumeration"] box = gui.radioButtons(self.controlArea, self, "pruning", box="Pruning", callback=self._invalidate_pruning) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False), 0, 0) self.max_depth_spin = gui.spin(box, self, "max_depth", minv=1, maxv=100, callback=self._invalidate_pruning, keyboardTracking=False) grid.addWidget( gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0) grid.addWidget(self.max_depth_spin, 1, 1) box = gui.radioButtons(self.controlArea, self, "selection_method", box="Selection", callback=self._selection_method_changed) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False), 0, 0) grid.addWidget( gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1, 0) self.cut_ratio_spin = gui.spin(box, self, "cut_ratio", 0, 100, step=1e-1, spinType=float, callback=self._selection_method_changed) self.cut_ratio_spin.setSuffix("%") grid.addWidget(self.cut_ratio_spin, 1, 1) grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False), 2, 0) self.top_n_spin = gui.spin(box, self, "top_n", 1, 20, callback=self._selection_method_changed) grid.addWidget(self.top_n_spin, 2, 1) box.layout().addLayout(grid) self.controlArea.layout().addStretch() box = gui.widgetBox(self.controlArea, "Output") gui.checkBox(box, self, "append_clusters", "Append cluster IDs", callback=self._invalidate_output) ibox = gui.indentedBox(box) name_edit = gui.lineEdit(ibox, self, "cluster_name") name_edit.editingFinished.connect(self._invalidate_output) cb = gui.comboBox( ibox, self, "cluster_role", callback=self._invalidate_output, items=["Attribute", "Class variable", "Meta variable"]) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, labelAlignment=Qt.AlignLeft, spacing=8) form.addRow("Name", name_edit) form.addRow("Place", cb) ibox.layout().addSpacing(5) ibox.layout().addLayout(form) ibox.layout().addSpacing(5) cb = gui.checkBox(box, self, "autocommit", "Commit automatically") b = gui.button(box, self, "Commit", callback=self.commit, default=True) gui.setStopper(self, b, cb, "_invalidated", callback=self.commit) self.scene = QGraphicsScene() self.view = QGraphicsView( self.scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) def axis_view(orientation): ax = pg.AxisItem(orientation=orientation, maxTickLength=7) scene = QGraphicsScene() scene.addItem(ax) view = QGraphicsView( scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) view.setFixedHeight(ax.size().height()) ax.line = SliderLine(orientation=Qt.Horizontal, length=ax.size().height()) scene.addItem(ax.line) return view, ax self.top_axis_view, self.top_axis = axis_view("top") self.mainArea.layout().setSpacing(1) self.mainArea.layout().addWidget(self.top_axis_view) self.mainArea.layout().addWidget(self.view) self.bottom_axis_view, self.bottom_axis = axis_view("bottom") self.mainArea.layout().addWidget(self.bottom_axis_view) self._main_graphics = QGraphicsWidget() self._main_layout = QGraphicsLinearLayout(Qt.Horizontal) self._main_layout.setSpacing(1) self._main_graphics.setLayout(self._main_layout) self.scene.addItem(self._main_graphics) self.dendrogram = DendrogramWidget() self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.dendrogram.selectionChanged.connect(self._invalidate_output) self.dendrogram.selectionEdited.connect(self._selection_edited) fm = self.fontMetrics() self.dendrogram.setContentsMargins(5, fm.lineSpacing() / 2, 5, fm.lineSpacing() / 2) self.labels = GraphicsSimpleTextList() self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.labels.setAlignment(Qt.AlignLeft) self.labels.setMaximumWidth(200) self.labels.layout().setSpacing(0) self._main_layout.addItem(self.dendrogram) self._main_layout.addItem(self.labels) self._main_layout.setAlignment(self.dendrogram, Qt.AlignLeft | Qt.AlignVCenter) self._main_layout.setAlignment(self.labels, Qt.AlignLeft | Qt.AlignVCenter) self.view.viewport().installEventFilter(self) self.top_axis_view.viewport().installEventFilter(self) self.bottom_axis_view.viewport().installEventFilter(self) self._main_graphics.installEventFilter(self) self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal) self.cut_line.valueChanged.connect(self._dendrogram_slider_changed) self.cut_line.hide() self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed) self.top_axis.line.valueChanged.connect(self._axis_slider_changed) self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed) self._set_cut_line_visible(self.selection_method == 1)
def __init__(self, game): super().__init__() self.game = game self.game.ui = self self.setWindowTitle('WordJuggler') self.resize(800, 600) self.setStyleSheet('QGroupBox { border:0; font:bold;' + 'padding:20px 10px; min-width:220px; }') self.board = BoardItem(game.width, game.height) self.rack = RackItem(game.rack_size, game.width, game.height) self.scene = QGraphicsScene() self.scene.setBackgroundBrush(QBrush(QColor('#f9ece0'))) self.scene.addItem(self.board) self.scene.addItem(self.rack) self.scene.setSceneRect(self.scene.itemsBoundingRect()) self.view = BoardView(self.scene, self) self.view.letterChanged.connect(self.letterChanged) self.ranking = QGroupBox('Rankings') self.rankings = QLabel() rankings = QVBoxLayout() rankings.addWidget(self.rankings) self.ranking.setLayout(rankings) self.statistic = QGroupBox('Statistics') self.statistics = QLabel() statistics = QVBoxLayout() statistics.addWidget(self.statistics) self.statistic.setLayout(statistics) self.move = QGroupBox('Last 10 Moves') self.moves = QLabel() moves = QVBoxLayout() moves.addWidget(self.moves) self.move.setLayout(moves) self.buttons = QVBoxLayout() self.buttons.setSpacing(3) self.continue_button = QPushButton('Place &Word') self.continue_button.setEnabled(False) self.continue_button.setFixedSize(130, 25) self.continue_button.clicked.connect(self.continueClicked) self.pass_button = QPushButton('&Pass') self.pass_button.setEnabled(False) self.pass_button.setFixedSize(130, 25) self.pass_button.clicked.connect(self.passClicked) self.exchange_button = QPushButton('&Exchange') self.exchange_button.setEnabled(False) self.exchange_button.setFixedSize(130, 25) self.exchange_button.clicked.connect(self.exchangeClicked) self.buttons.addWidget(self.exchange_button, alignment=Qt.AlignCenter) self.buttons.addWidget(self.pass_button, alignment=Qt.AlignCenter) self.buttons.addWidget(self.continue_button, alignment=Qt.AlignCenter) information = QVBoxLayout() information.setMargin(20) information.setSpacing(20) information.addWidget(self.ranking) information.addWidget(self.statistic) information.addWidget(self.move) information.addStretch() information.addLayout(self.buttons) layout = QHBoxLayout() layout.setSpacing(0) layout.setMargin(0) layout.addWidget(self.view) layout.addLayout(information) self.setLayout(layout) self.show() for player in self.game.players: player.played_cb = self.playerDone self.playerNext()