Exemplo n.º 1
0
class NoBrowser(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.initUI()

    def initUI(self):
        self.connect(self.ui.bBack, QtCore.SIGNAL('clicked()'),
                     self.ui.webView.back)
        self.connect(self.ui.bForward, QtCore.SIGNAL('clicked()'),
                     self.ui.webView.forward)
        self.connect(self.ui.url, QtCore.SIGNAL('returnPressed()'),
                     self.browse)

    def browse(self):
        url = self.ui.url.text() if self.ui.url.text() else self.default_url
        print url
        self.ui.webView.load(QtCore.QUrl(url))
        self.ui.webView.show()

    def mousePressEvent(self, event):
        self.offset = event.pos()

    def mouseMoveEvent(self, event):
        x = event.globalX()
        y = event.globalY()
        x_w = self.offset.x()
        y_w = self.offset.y()
        self.move(x - x_w, y - y_w)
Exemplo n.º 2
0
class NoBrowser(QtGui.QMainWindow):

  def __init__(self, parent=None):
    QtGui.QWidget.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
    self.initUI()
    
  def initUI(self):
    self.connect(self.ui.bBack, QtCore.SIGNAL('clicked()'), self.ui.webView.back)
    self.connect(self.ui.bForward, QtCore.SIGNAL('clicked()'), self.ui.webView.forward)
    self.connect(self.ui.url, QtCore.SIGNAL('returnPressed()'), self.browse)

  def browse(self):
    url = self.ui.url.text() if self.ui.url.text() else self.default_url
    print url
    self.ui.webView.load(QtCore.QUrl(url))
    self.ui.webView.show()

  def mousePressEvent(self, event):
    self.offset = event.pos()

  def mouseMoveEvent(self, event):
    x=event.globalX()
    y=event.globalY()
    x_w = self.offset.x()
    y_w = self.offset.y()
    self.move(x-x_w, y-y_w)
Exemplo n.º 3
0
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(MainWindow)
        self.set_lcd_1()
        self.set_dial_1()
        self.set_lcd_2()
        self.set_dial_2()
        self.set_lcd_3()
        self.set_dial_3()
        self.set_lcd_4()
        self.set_dial_4()

        self.ui.pushButton.clicked.connect(self.ui.initialize)
        self.ui.pushButton_2.clicked.connect(self.ui.stop)
        self.ui.pushButton_3.clicked.connect(self.ui.execute)
        self.ui.pushButton_4.clicked.connect(self.ui.run_pump_1)
        self.ui.pushButton_5.clicked.connect(self.ui.run_pump_2)
        self.ui.pushButton_6.clicked.connect(self.ui.run_pump_3)
        self.ui.pushButton_7.clicked.connect(self.ui.run_pump_4)
        self.ui.pushButton_8.clicked.connect(self.ui.spectrum_analysis)

        # self.ui.initialize()

        MainWindow.show()
        sys.exit(app.exec_())
Exemplo n.º 4
0
    def __init__(self):

        super(myApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #combobox content
        self.ports = serial.tools.list_ports.comports()
        for i in self.ports:
            self.ui.comboBox.addItem(str(i))

        baud = [
            "300", "1200", "2400", "4800", "9600", "19200", "38400", "57600",
            "74880", "115200", "230400", "250000", "500000", "1000000",
            "2000000"
        ]
        for i in baud:
            self.ui.comboBox_2.addItem(i)
        self.ui.comboBox_2.setCurrentText(baud[4])

        self.ui.label_3.setText(
            "<font color=red>COM port bağlı değil!!!</font>")
        self.ui.textEdit.setReadOnly(True)

        #

        self.mySerial = serialThreadClass()
        self.mySerial.message.connect(self.messageTextEdit)  #def
        self.mySerial.start()

        #button
        self.ui.pushButton.clicked.connect(self.serialConnect)  #def
        self.ui.pushButton_2.clicked.connect(self.serialDisconnect)  #def
Exemplo n.º 5
0
	def __init__(self):
		Ui_MainWindow.__init__(self)
		self.window = QtWidgets.QMainWindow()
		self.setupUi(self.window)
		self.registry = None
		self.tree_root = None
		self.search_window = None
		self.mode_value.setText("Все")
		self.open_action.triggered.connect(self.open_action_func)
		self.export_a_action.triggered.connect(self.export_a_action_func)
		self.export_m_action.triggered.connect(self.export_m_action_func)
		self.value_search_action.triggered.connect(self.search_func)
		self.about.triggered.connect(self.about_func)
		self.exit_action.triggered.connect(self.exit_func)
		self.treeWidget.clicked.connect(self.tree_item_click)
		self.view_all.triggered.connect(self.show_all)
		self.change_name.triggered.connect(self.change_name_func)
		self.change_value.triggered.connect(self.change_value_func)
		self.view_deleted.triggered.connect(self.show_only_deleted)
		self.view_nondeleted.triggered.connect(self.show_not_deleted)
		self.save_action.triggered.connect(self.save_changes_function)
		self.renew_action.triggered.connect(self.reload_function)
		self.tableWidget.hideColumn(4)
		self.fname = None
		self.window.show()
Exemplo n.º 6
0
    def __init__(self):
        super().__init__()
        self.ecopainter = QtGui.QPainter()
        self.trois_D = False
        self.nb_iter = 0
        self.fraction = 0.5
        self.puiss = 1
        self.terrain = None
        self.figure2D = self.figure3D = Figure() #figsize=(width, height), dpi=dpi
        self.cours_eau = None

        # Configuration de l'interface utilisateur.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.actionQuitter, QtCore.SIGNAL("triggered()"), self.quit)
        QtCore.QObject.connect(self.ui.Iterations,QtCore.SIGNAL("valueChanged(int)"), self.nbIter)
        self.ui.bruit_lin.toggled.connect(self.bruitLin)
        self.ui.bruit_quadra.toggled.connect(self.bruitQua)
        self.ui.bruit_racine.toggled.connect(self.bruitRac)
        QtCore.QObject.connect(self.ui.val_fraction,QtCore.SIGNAL("valueChanged(double)"),self.frac)
        self.ui.deuxD.toggled.connect(self.deuxDim)
        self.ui.troisD.toggled.connect(self.troisDim)
        QtCore.QObject.connect(self.ui.generer_bouton,QtCore.SIGNAL("clicked()"),self.generer)

        QtCore.QObject.connect(self.ui.val_fraction, QtCore.SIGNAL("valueChanged(double)"), self.change_val_doubleSpin)
        QtCore.QObject.connect(self.ui.Fraction, QtCore.SIGNAL("valueChanged(int)"), self.change_position_slider)

        QtCore.QObject.connect(self.ui.ajouter_cours_bouton,QtCore.SIGNAL("clicked()"),self.ajoute_cours)
Exemplo n.º 7
0
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.solve.clicked.connect(self.solver)
        self.ui.review.clicked.connect(self.reviewer)
Exemplo n.º 8
0
class MainWindow(object):
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(MainWindow)
        self.set_lcd_1()
        self.set_dial_1()
        self.set_lcd_2()
        self.set_dial_2()
        self.set_lcd_3()
        self.set_dial_3()
        self.set_lcd_4()
        self.set_dial_4()

        self.ui.pushButton.clicked.connect(self.ui.initialize)
        self.ui.pushButton_2.clicked.connect(self.ui.stop)
        self.ui.pushButton_3.clicked.connect(self.ui.execute)
        self.ui.pushButton_4.clicked.connect(self.ui.run_pump_1)
        self.ui.pushButton_5.clicked.connect(self.ui.run_pump_2)
        self.ui.pushButton_6.clicked.connect(self.ui.run_pump_3)
        self.ui.pushButton_7.clicked.connect(self.ui.run_pump_4)
        self.ui.pushButton_8.clicked.connect(self.ui.spectrum_analysis)

        # self.ui.initialize()

        MainWindow.show()
        sys.exit(app.exec_())

    # 设置LCD数字1
    def set_lcd_1(self):
        self.ui.lcdNumber.display(self.ui.dial.value())

    # 刻度盘信号槽1
    def set_dial_1(self):
        self.ui.dial.valueChanged['int'].connect(self.set_lcd_1)

    # 设置LCD数字2
    def set_lcd_2(self):
        self.ui.lcdNumber_2.display(self.ui.dial_2.value())

    # 刻度盘信号槽2
    def set_dial_2(self):
        self.ui.dial_2.valueChanged['int'].connect(self.set_lcd_2)

    # 设置LCD数字3
    def set_lcd_3(self):
        self.ui.lcdNumber_3.display(self.ui.horizontalSlider.value())

    # 刻度盘信号槽3
    def set_dial_3(self):
        self.ui.horizontalSlider.valueChanged['int'].connect(self.set_lcd_3)

    # 设置LCD数字3
    def set_lcd_4(self):
        self.ui.lcdNumber_4.display(self.ui.horizontalSlider_2.value())

    # 刻度盘信号槽3
    def set_dial_4(self):
        self.ui.horizontalSlider_2.valueChanged['int'].connect(self.set_lcd_4)
Exemplo n.º 9
0
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(MainWindow)
        MainWindow.show()

        # Стандартные характеристики зарядов
        self.radius = DEFAULT_RADIUS
        self.min_width = self.min_height = self.radius
        self.max_width = self.ui.graphicsView.width() - self.radius
        self.max_height = self.ui.graphicsView.height() - self.radius
        self.max_color_value = 0

        # Инициализируем графическую сцену и привязываем её к graphicsView
        self.scene = QGraphicsScene()
        self.ui.graphicsView.setScene(self.scene)

        # Выделенные заряды на сцене
        self.selected_charges = []

        # Создаём экземпляр класса событий
        self.events = Events()
        self.events.focus_in_event[Charge].connect(self.enable_editing)
        self.events.focus_out_event.connect(self.disable_editing)
        self.events.mouse_press_event[Charge].connect(self.delete_connections)
        self.events.mouse_release_event.connect(self.add_connections)

        # Инициализируем обработчики событий от элементов пользовательского интерейса
        self.ui.addCharge.clicked.connect(self.add_charge)
        self.ui.deleteCharge.clicked.connect(self.delete_charge)
        self.ui.chargeValue.editingFinished.connect(self.change_charge_value)

        # Запускаем бесконечный цикл обработки событий от пользовательского интерфейса
        sys.exit(app.exec_())
Exemplo n.º 10
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.play_sound)
        self.ui.pushButton_2.clicked.connect(self.stop_sound)
        self.resized.connect(self.resize_plot)
Exemplo n.º 11
0
    def __init__(self):

        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.Start_button.clicked.connect(self.start_clicked)
        self.ui.Pause_button.clicked.connect(self.pause_clicked)
        self.ui.Save_button.clicked.connect(self.save_clicked)
Exemplo n.º 12
0
    def __init__(self):
        global ftp_images_folder
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.labelShowFilePath.setText(ftp_images_folder)
        self.ui.shootBtn.clicked.connect(self.shoot_btnClicked)
        self.ui.spinBox.valueChanged.connect(self.spin_valueChanged)
        self.ui.btnFileDialog.clicked.connect(self.btnFileDialog_clicked)
Exemplo n.º 13
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        global ftp_images_folder
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.labelShowFilePath.setText(ftp_images_folder)
        self.ui.shootBtn.clicked.connect(self.shoot_btnClicked)
        self.ui.spinBox.valueChanged.connect(self.spin_valueChanged)
        self.ui.btnFileDialog.clicked.connect(self.btnFileDialog_clicked)

    def btnFileDialog_clicked(self):
        try:

            directoryName = QFileDialog.getExistingDirectory(
                self, "getExistingDirectory", "./")
            if directoryName:

                self.ui.labelShowFilePath.setText(directoryName)
                global ftp_images_folder
                ftp_images_folder = directoryName + "/"
                print(ftp_images_folder)

        except:
            print(sys.exc_info()[0])

    def spin_valueChanged(self):
        global time_interval
        time_interval = self.ui.spinBox.value()
        print(time_interval)

    def shoot_btnClicked(self):
        global ftp_images_folder
        if (os.path.isdir(ftp_images_folder)):
            t = time.time()
            global time_interval
            print("timeinterval=:")
            print(time_interval)
            sendTime = str(int(t)) + "," + str(time_interval) + "," + str(
                ftp_images_folder)
            client.publish(pub_topic, sendTime)

        else:
            try:
                print("else")
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle("Photo Manager")
                msg.setText("Please set a Folder to save Photos First!")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
            except:
                print(sys.exc_info()[0])
Exemplo n.º 14
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # Genero grafica con Matplotlib

        seno = WidgetPlot(self)
        #PlotCanvas()
        self.ui.verticalLayout_nyquist.addWidget(seno)

        coseno = WidgetPlot(self)
        self.ui.verticalLayout_bode.addWidget(coseno)
Exemplo n.º 15
0
 def __init__(self):
     self.dljActive = False
     self.sljActive = False
     self.tubeActive = False
     self.stringEmpty = False
     self.Hartsmith = HartSmith
     self.Volkersen = volkersen
     self.failure = failureMode
     self.app = QtWidgets.QApplication(sys.argv)
     self.MainWindow = QtWidgets.QMainWindow()
     self.ui = Ui_MainWindow()
     self.startUi()
Exemplo n.º 16
0
class Gui:

    def __init__(self):
        self.curr = 0
        self.app = QApplication(sys.argv)
        self.fileManager = QFileDialog()
        self.fileManager.setFileMode(self.fileManager.DirectoryOnly)
        self.window = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.window)
        self.thread = Worker()
        self.connect()

    def onDownloadButton(self):
        url = str(self.ui.urlEdit.text())
        dir =  str(self.ui.dirEdit.text())
        if(self.ui.checkBox.isChecked()):
            watch = True
        else:
            watch = False
        self.thread.getVar(dir,url,watch)
        self.thread.start()


    def onSelectFolder(self):

        Fdialog = QFileDialog()
        Fdialog.setFileMode(QFileDialog.DirectoryOnly)
        if Fdialog.exec_():
            folderPath = QStringList(Fdialog.selectedFiles())
            self.ui.dirEdit.setText(folderPath.takeFirst())

    def onError(self, type):
        dialog = QDialog(self.window)
        text  = QLabel(dialog)
        if(type is "url"):
            text.setText("URL is invalid")
        else:
            text.setText("DIR is invalid")
        dialog.exec_()

    def getMax(self,max):
        self.ui.progressBar.setRange(0,max)


    def update(self,n):
        self.ui.progressBar.setValue(n)

    def connect(self):
        QObject.connect(self.ui.pushButton,SIGNAL("clicked()"),self.onDownloadButton)
        QObject.connect(self.ui.toolButton,SIGNAL("clicked()"),self.onSelectFolder)
        QObject.connect(self.thread,SIGNAL("update(int)"),self.update)
    def __init__(self, *arg, **kwargs):
        super().__init__(*arg, **kwargs)

        #my code goes here
        # self.button = qtw.QPushbutton("click me")

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.select_btn.clicked.connect(self.loop_video)

        # my ui code ends ere

        self.show()
class Mainwindow(qtw.QMainWindow):
    def __init__(self, *arg, **kwargs):
        super().__init__(*arg, **kwargs)

        #my code goes here
        # self.button = qtw.QPushbutton("click me")

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.select_btn.clicked.connect(self.loop_video)

        # my ui code ends ere

        self.show()

    def callback(self):
        print("hello there")

    def loop_video(self):
        print("ok")
        fname = qtw.QFileDialog.getOpenFileName(
            self, 'Open file', 'c:\\',
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")
        videoname_url = str(fname[0])
        self.ui.label_videoname.setText(videoname_url)

        data_list = []
        media_info = MediaInfo.parse(videoname_url)
        for track in media_info.tracks:

            if track.track_type == "Video":
                print("Bit rate: {t.bit_rate}, Frame rate: {t.frame_rate}, "
                      "Format: {t.format}".format(t=track))
                print("Duration (raw value):", track.duration)
                #print("Duration (other values:")
                pprint(track.other_duration)
                self.ui.textEdit_data.append(
                    "Bit rate: {t.bit_rate}, Frame rate: {t.frame_rate}, "
                    "Format: {t.format}".format(t=track))
                self.ui.textEdit_data.append("Duration (raw value):" +
                                             str(track.duration) + '\n')
                self.ui.textEdit_data.append("Duration (other values:")
                #self.ui.textEdit_data.setText(self.ui.textEdit_data.text() + str(track ))

            elif track.track_type == "Audio":
                print("Track data:")
                pprint(track.to_data())
                data_dict = track.to_data()
                for key in data_dict:
                    print(key)
Exemplo n.º 19
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        gridLayout = QGridLayout(centralWidget)
        gridLayout.addWidget(self.ui.label, 1, 0, alignment=Qt.AlignCenter)
        gridLayout.addWidget(self.ui.label_2, 0, 0, alignment=Qt.AlignCenter)
        gridLayout.addWidget(self.ui.pushButton, 6, 0)
        gridLayout.addWidget(self.ui.pushButton2, 5, 0)
        gridLayout.addWidget(self.ui.comboBox, 2, 0)
        gridLayout.addWidget(self.ui.comboBox2, 3, 0)
        gridLayout.addWidget(self.ui.comboBox3, 4, 0)
Exemplo n.º 20
0
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.QuitBtn.clicked.connect(QtWidgets.QApplication.instance().quit)
        self.ui.translateBtn.clicked.connect(self.translate)
        
    def translate(self):
        in_text = self.ui.input.text()
        if in_text:
            out_text = search_translation(str(in_text))
            if out_text:
                self.ui.output.setText("Перевод слова: " + out_text)
            else:
                self.ui.output.setText("Вы ввели неверное значение.\nПожалуйста, проверьте введённые данные и попробуйте ещё раз.")
Exemplo n.º 21
0
 def __init__(self, parent=None):
   #Instance variables
   self.chatLines = []
   self.consoleLines = []
   self.lastServerLine = 'first run'
   self.onlineDict = {}
   self.pluginsDict = {} 
   
   #Initialize a QTimer to run background updates (online players, status, new chat messages, etc)
   self.repeatingTimer = QtCore.QTimer()
   self.singleTimer = QtCore.QTimer() #Not used...
   
   self.s=Server()
   QtGui.QWidget.__init__(self, parent)
   self.ui = Ui_MainWindow()
   self.ui.setupUi(self)
   self.initUI()
   
   self.startRepeatingTimer()
   self.findPlugins() #Find the currently installed plugins by searching the plugin folder
   
   #Set the start/stop button text
   if self.s.status():
     self.ui.pushButtonStopStart.setText('Stop Server')
   else:
     self.ui.pushButtonStopStart.setText('Start Server')
Exemplo n.º 22
0
    def __init__(self):
        super().__init__()
        # Configuration de l'interface utilisateur.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Ajout du fond d'écran
        indice_background = str(np.random.randint(0, 4))
        print(indice_background)
        self.setStyleSheet(
            "QMainWindow{ background-image: url(images/textures/texture_" +
            indice_background + "); }")

        self.put_sound = QSound("sounds/effect/put.wav")
        self.background_sound = QSound(None)

        # Création d'une partie
        #self.game = Game(UI = self)

        #création du thread gérant le jeu lui même
        self.thread = ThreadGame(UI=self)

        #connection des signaux provenant du thread
        self.thread.signal_init_grid.connect(self.init_grid_void)
        self.thread.signal_poser.connect(self.poser)
        self.thread.signal_main.connect(self.afficher_main)
        self.thread.signal_choix_domino.connect(self.calque_choix_domino)
        self.thread.signal_choix_extremite.connect(self.calque_choix_extremite)
        self.thread.signal_refresh_plateau.connect(self.refresh_plateau)
        self.thread.signal_choix_orientation.connect(
            self.calque_choix_orientation)
        self.thread.signal_choix_mode.connect(self.calque_choix_mode)
        self.thread.signal_choix_pseudo.connect(self.calque_choix_pseudo)
        self.thread.signal_message_box.connect(self.afficher_message_box)
        self.thread.signal_choix_recommencer.connect(self.choix_recommencer)
        self.thread.signal_init_main.connect(self.init_main)
        self.thread.signal_terminus.connect(self.terminus)
        self.thread.signal_background_sound.connect(self.init_background_sound)
        self.thread.signal_sound_fx.connect(self.sound_fx)
        self.thread.signal_nb_joueur.connect(self.choix_nombre_joueur)
        self.thread.signal_go.connect(self.go)

        #démarage du thread et donc de Game
        self.thread.start()

        #Liste des layouts de dominos de la main
        self.hand_layout_container = []
Exemplo n.º 23
0
 def __init__(self, parent=None):
     super(StartQT4, self).__init__(parent)
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.showMaximized()
     # Conexao de elementos da interface grafica
     self.fig = plt.figure()
     self.canvas = FigureCanvas(self.fig)
     self.toolbar = NavigationToolbar(self.canvas, self)
     #QtCore.QObject.connect(self.ui.btn_runpoint, QtCore.SIGNAL('clicked()'), self.dynamic_analysis)
     QtCore.QObject.connect(self.ui.btn_detectar,
                            QtCore.SIGNAL('clicked()'),
                            self.instrument_detection)
     QtCore.QObject.connect(self.ui.btn_conectar,
                            QtCore.SIGNAL('clicked()'),
                            self.instrument_connection)
     QtCore.QObject.connect(self.ui.btn_opencal, QtCore.SIGNAL('clicked()'),
                            self.open_calibration)
     QtCore.QObject.connect(self.ui.btn_shortcal,
                            QtCore.SIGNAL('clicked()'),
                            self.short_calibration)
     QtCore.QObject.connect(self.ui.btn_run, QtCore.SIGNAL('clicked()'),
                            self.run_analysis)
     QtCore.QObject.connect(self.ui.toolbtn_savepath,
                            QtCore.SIGNAL('clicked()'), self.get_save_path)
     QtCore.QObject.connect(self.ui.btn_plot, QtCore.SIGNAL('clicked()'),
                            self.plot_test)
     QtCore.QObject.connect(self.ui.btn_plot_permi,
                            QtCore.SIGNAL('clicked()'), self.plot_erei)
     QtCore.QObject.connect(self.ui.btn_plot_RC, QtCore.SIGNAL('clicked()'),
                            self.plot_RC)
     QtCore.QObject.connect(self.ui.btn_plot_ZT, QtCore.SIGNAL('clicked()'),
                            self.plot_ZT)
     QtCore.QObject.connect(self.ui.btn_plot_ZrZi,
                            QtCore.SIGNAL('clicked()'), self.plot_ZrZi)
     QtCore.QObject.connect(self.ui.actionImportar_Dados,
                            QtCore.SIGNAL('triggered()'),
                            self.importar_dados)
     QtCore.QObject.connect(self.ui.blt_skipcal, QtCore.SIGNAL('clicked()'),
                            self.skip_calibration)
     self.is_open_calibrated = False
     self.is_short_calibrated = False
     layout = self.ui.verticalLayout
     layout.addWidget(self.toolbar)
     layout.addWidget(self.canvas)
Exemplo n.º 24
0
 def __init__(self, parent=None):
     super(ControlMainWindow, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.settings = QSettings('Classificador', 'Independente')
     self._prepare_settings()
     self._abrir_pasta(self.settings.value('pasta_imagens'))
     # Caminho da pasta com as configurações de parâmetro.
     self.pasta_settings = os.path.join(self.settings.value('pasta_imagens'), 'images_settings')
    def __init__(self,*arg,**kwargs):
        super().__init__(*arg,**kwargs)

        #my code goes here
        # self.button = qtw.QPushbutton("click me")

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.select_btn.clicked.connect(self.show_data)
        self.ui.audio_btn.clicked.connect(self.cut_audio)
        self.ui.sequence_btn.clicked.connect(self.convert_to_images)
        self.ui.screenshots_btn.clicked.connect(self.generate_screenstots)
        self.ui.convert_codec_btn.clicked.connect(self.convert_codec)
        self.ui.convert_codec_btn.clicked.connect(self.convert_codec)
        self.ui.srt_btn.clicked.connect(self.extract_srt)


        self.show()
Exemplo n.º 26
0
 def __init__(self):
     self.curr = 0
     self.app = QApplication(sys.argv)
     self.fileManager = QFileDialog()
     self.fileManager.setFileMode(self.fileManager.DirectoryOnly)
     self.window = QMainWindow()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self.window)
     self.thread = Worker()
     self.connect()
Exemplo n.º 27
0
    def __init__(self):
        os.system("cls")
        # init params
        self.personage_path = 'picture'
        self.process_mode = -1
        self.cap_index = 0  #摄像头序号,本地,网络转本地,网络摄像头
        self.webcamera_url = 'http://192.168.4.1/capture'
        self.cap = cv2.VideoCapture(0)
        self.isAuto = False
        self.count = 0

        self.app = QApplication(sys.argv)
        self.mainWindow = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.mainWindow)
        self.FormLoad()
        self.mainWindow.show()

        sys.exit(self.app.exec_())
Exemplo n.º 28
0
    def __init__(self):
        super(self.__class__, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.button_upload.clicked.connect(self.on_button_upload_clicked_1)
        self.ui.button_browse.clicked.connect(self.on_button_browse_clicked_1)
        self.ui.button_del.clicked.connect(self.on_button_del_clicked_1)

        self.ui.radio_width.toggled.connect(self.on_radio_width_toggled)
        self.ui.radio_height.toggled.connect(self.on_radio_height_toggled)
        self.ui.radio_both.toggled.connect(self.on_radio_both_toggled)
        self.ui.radio_noscale.toggled.connect(self.on_radio_dontscale_toggled)

        self.show()
        self.nam = 0
        self.rep = 0
        self.req = 0
        self.f = 0
        self.filecount = 0
Exemplo n.º 29
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.pointsList = np.matrix([])
        # here we connect signals with our slots
        self.ui.webView.setHtml(html)
        self.ui.webView.loadFinished.connect(self.loadFinished)

        QtCore.QObject.connect(self.ui.loadButton, QtCore.SIGNAL("clicked()"),
                               self.getPoints)
        QtCore.QObject.connect(self.ui.plotButton, QtCore.SIGNAL("clicked()"),
                               self.plotWaypoints)
        QtCore.QObject.connect(self.ui.saveButton, QtCore.SIGNAL("clicked()"),
                               self.saveWaypoints)

        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop)
Exemplo n.º 30
0
class main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.button.clicked.connect(self.clickme)
        self.ui.pushButton.clicked.connect(self.pushclick)

    def clickme(self):
        self.text = self.ui.textEdit.toPlainText()
        self.key = Fernet.generate_key()
        f = Fernet(self.key)
        texts = self.text.encode("utf-8")
        self.token = f.encrypt(texts)
        self.ui.textEdit_2.setText(str(self.token))

    def pushclick(self):
        f = Fernet(self.key)
        dec = f.decrypt(self.token)
        decode = dec.decode()
        self.ui.textEdit_2.setText(str(decode))
Exemplo n.º 31
0
    def __init__(self):
        super(App, self).__init__()
        self._window = QMainWindow()
        self._window.setStyleSheet(qss)
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self._window)
        self._window.setWindowFlags(Qt.FramelessWindowHint)
        self._window.show()

        self._is_edit_mode = False
        self._data = None
        self._pos = 0
        self._items = None
        self.t = None
        self.thread_stop = False

        self._window.mousePressEvent = self.mousePressEvent
        self._window.mouseMoveEvent = self.mouseMoveEvent

        # resize table header
        table_width = self._ui.task_table.width()
        self._ui.task_table.setColumnWidth(0, ceil(table_width * 0.4))
        for index in range(1, self._ui.task_table.horizontalHeader().count()):
            self._ui.task_table.horizontalHeader().setSectionResizeMode(
                index, QHeaderView.Stretch)

        year = datetime.now().year
        month = datetime.now().month
        day = datetime.now().day

        self._ui.start_date.setDate(QDate(year, month, day))
        self._ui.end_date.setDate(QDate(year, month, day))
        self._ui.frame.setHidden(True)
        self._is_edit_mode = True
        self.set_tray_icon()
        self.signals()
        self.get_data()
        self.on_load(self._items)
        self.move_app('topright')
        self.job_thread()
Exemplo n.º 32
0
	def initUI(self):
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		exitAction = QAction(QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(qApp.quit)
		self.statusBar()
		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(exitAction)
		self.setWindowTitle('Timer')
		self.isShown = False
Exemplo n.º 33
0
  def __init__(self, parent=None):
    
    #Are we local or remote?
    self.remote = True

    #Instantiate a minecraft server object
    self.s=Server(remote=self.remote)

    #The usual
    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.initUI()

    #Instance variables
    self.chatLines = []
    self.consoleLines = []
    self.onlineDict = {}
    self.pluginsDict = {} 

       #Set the start/stop button text
    if self.s.status():
      self.ui.pushButtonStopStart.setText('Stop Server')
    else:
      self.ui.pushButtonStopStart.setText('Start Server')

    if self.remote:
      print 'spawning remote thread'
      self.connect(self, QtCore.SIGNAL('newRemoteLines'), self.routeServerLines)
      self.connect(self, QtCore.SIGNAL('pluginsDict'), self.remotePlugins)
      self.thread = GenericThread(self.remoteConn)
      self.thread.start()
      print 'thread started'
    else:
      #Instantiate a qThreadWatcher() to monitor server.log for changes and connect its signal
      #to newLineDetected.
      self.fileWatcher = QtCore.QFileSystemWatcher(self)
      self.fileWatcher.addPath(os.path.join(self.s.bukkitDir, 'server.log'))
      self.connect(self.fileWatcher, QtCore.SIGNAL('fileChanged(QString)'), self.newLineDetected)

      #Find the currently installed plugins by searching the plugin folder
      self.findPlugins()

      #On app boot, read til the last time the server was started
      self.lastServerLine = ' [INFO] Stopping server'
      self.newLineDetected()
     
     #Initialize a QTimer to run and connect it to ticToc
      self.repeatingTimer = QtCore.QTimer()
      self.repeatingTimer.start(1000)      
      self.connect(self.repeatingTimer, QtCore.SIGNAL('timeout()'), self.ticToc)
Exemplo n.º 34
0
 def __init__(self):
     super(MyWindow, self).__init__()
     self.files_to_save_list = []
     self.input_path = ''
     self.output_path = ''
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.Input_dir_toolButton.clicked.connect(self.input_dir_tool_button_clicked)
     self.ui.Output_dir_toolButton.clicked.connect(self.output_dir_tool_button_clicked)
     self.ui.F01X.stateChanged.connect(self.chooseF01X)
     self.ui.F02X.stateChanged.connect(self.chooseF02X)
     self.ui.F6DX.stateChanged.connect(self.chooseF6DX)
     self.ui.FC5X.stateChanged.connect(self.chooseFC5X)
     self.ui.F20X.stateChanged.connect(self.chooseF20X)
     self.ui.FA7X.stateChanged.connect(self.chooseFA7X)
     self.ui.F6BX.stateChanged.connect(self.chooseF6BX)
     self.ui.Start.clicked.connect(self.start_clicked)
     self.ui.analysis_date.setDateTime(QtCore.QDateTime.currentDateTime())
     self.ui.analysis_date.setCalendarPopup(True)
     self.ui.analysis_date.dateChanged.connect(self.update_date)
     self.analysis_date = None
     self.ui.actionSettings.triggered.connect(self.show_settings_window)
     self.sett_content = sett_content
Exemplo n.º 35
0
    def __init__(self):

        self.main_win = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_win)
        self.Dados = []
        self.Salas = []
        self.tabela = self.frame()
        self.distribuir = ['sala1', 'sala2', 'café1', 'café2']

        #BOTÕES PARA MUDAR AS PÁGINAS NA APLICAÇÃO
        self.ui.TELAS.setCurrentWidget(self.ui.page3)
        self.ui.botao1.clicked.connect(self.showtela1)
        self.ui.botao2.clicked.connect(self.showtela2)
        self.ui.botao3.clicked.connect(self.showtela3)
        self.ui.botao4.clicked.connect(self.showtela4)
        self.ui.botao5.clicked.connect(self.showtela5)
        #BOTÕES DE INTERAÇÃO
        self.ui.botao4_5.clicked.connect(self.cadastrarparticipantes)
        self.ui.botao4_5.clicked.connect(self.mostrarframe)
        self.ui.botao4_6.clicked.connect(self.cadastrarsalas)
        self.ui.botao4_6.clicked.connect(self.frameSalas)
        self.ui.botao4_6.clicked.connect(self.mostrar_frame_salas)
Exemplo n.º 36
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()

# defining Widgets

        self.url = QLineEdit()     # for the URl Box
        self.save_location = QLineEdit()     #Address of saving the file
        self.progress = QProgressBar()
        self.downloadBtn = QPushButton("Download", self)  # Download Button
#        self.downloadBtn.clicked.connect(self.download)  # Conncet Button to Download Event
        self.browse = QPushButton("Browse")
#        self.browse.clicked.connect(self.saveFileDialog)
        self.urlparse = QLineEdit()
        self.sizelbl = QLabel()
        self.parserbtn = QPushButton("Parse", self)  # Parser Button
#        self.parserbtn.clicked.connect(self.parsing)
        self.urlparse.setPlaceholderText("Insert Link To parse")
        self.url.setPlaceholderText("URL")
        self.save_location.setPlaceholderText("File Save Location")
        self.txtbox = QTextBrowser()
Exemplo n.º 37
0
 def __init__(self, parent=None):
 
   #Instance variables
   self.chatLines = []
   self.consoleLines = []
   self.lastServerLine = ''
   
   #Initialize a QTimer to run background updates (online players, status, new chat messages, etc)
   self.repeatingTimer = QtCore.QTimer()
   self.singleTimer = QtCore.QTimer()
   
   self.s=Server()
   QtGui.QWidget.__init__(self, parent)
   self.ui = Ui_MainWindow()
   self.ui.setupUi(self)
   self.initUI()
   
   self.startRepeatingTimer()
   self.sendMessageClicked()
   self.consoleClicked()
   self.onlineClicked()
Exemplo n.º 38
0
class MyServer(QtGui.QMainWindow):
  
  def __init__(self, parent=None):
    #Instance variables
    self.chatLines = []
    self.consoleLines = []
    self.lastServerLine = 'first run'
    self.onlineDict = {}
    self.pluginsDict = {} 
    
    #Initialize a QTimer to run background updates (online players, status, new chat messages, etc)
    self.repeatingTimer = QtCore.QTimer()
    self.singleTimer = QtCore.QTimer() #Not used...
    
    self.s=Server()
    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.initUI()
    
    self.startRepeatingTimer()
    self.findPlugins() #Find the currently installed plugins by searching the plugin folder
    
    #Set the start/stop button text
    if self.s.status():
      self.ui.pushButtonStopStart.setText('Stop Server')
    else:
      self.ui.pushButtonStopStart.setText('Start Server')
    
  def initUI(self):
    self.connect(self.ui.pushButtonStopStart, QtCore.SIGNAL('clicked()'), self.stopStartClicked)
    self.connect(self.ui.lineEditMessage, QtCore.SIGNAL('returnPressed()'), self.sendChat)
    self.connect(self.ui.lineEditConsole, QtCore.SIGNAL('returnPressed()'), self.sendConsole)
    self.connect(self.ui.treeWidgetPluginList, QtCore.SIGNAL('itemSelectionChanged()'), self.pluginNameClicked)
    
    #Connect the timer
    self.connect(self.repeatingTimer, QtCore.SIGNAL('timeout()'), self.ticToc)


#####################
#GUI control methods
#####################

  #Start or stop the server
  def stopStartClicked(self):
    if self.s.status():
      self.s.stop()
      self.updateStatusBar()
      self.ui.pushButtonStopStart.setText('Start Server')
    else:
      self.s.start()
      self.updateStatusBar()
      self.ui.pushButtonStopStart.setText('Stop Server')  

  def sendChat(self):
    message = str(self.ui.lineEditMessage.text())
    self.ui.lineEditMessage.clear()   
    if message != '':
      self.s.message(message)
    self. updateChatDisplay([])
          
  def updateChatDisplay(self, chatLines): 
    for line in chatLines:
      fixedLine = line[5:19] + line[26:]
      width = self.ui.treeWidgetChat.columnWidth(0)
      fixedLine = utils.wordWrap(width-5, fixedLine)
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetChat)
      a.setText(0, fixedLine)
    if len(chatLines):
      self.ui.treeWidgetChat.scrollToItem(a)
      self.chatLines.extend(chatLines)

  def sendConsole(self):
    message = str(self.ui.lineEditConsole.text())
    self.ui.lineEditConsole.clear()   
    if message != '':
      self.s.command(message)
    self. updateConsoleDisplay([])
          
  def updateConsoleDisplay(self, consoleLines): 
    for line in consoleLines:
      fixedLine = line[5:19] + line[26:]
      width = self.ui.treeWidgetConsole.columnWidth(0)
      fixedLine = utils.wordWrap(width-5, fixedLine)
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetConsole)
      a.setText(0, fixedLine)
    if len(consoleLines):
      self.ui.treeWidgetConsole.scrollToItem(a)
      self.consoleLines.extend(consoleLines)
  
  def updatePlayersDisplay(self):
    self.ui.treeWidgetPlayersList.clear()
    for name in self.onlineDict:
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetPlayersList)
      a.setText(0, name)
      childrenList = []
      for key in self.onlineDict[name]:
        w = QtGui.QTreeWidgetItem(a)
        w.setText(0, str(key) + ': ' + str(self.onlineDict[name][key]))
        a.insertChild(0, w)
  
  def updatePluginsList(self):
    for pluginName in self.pluginsDict.keys():
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetPluginList)
      a.setText(0, str(pluginName))
      
  def pluginNameClicked(self):
    pluginName = str(self.ui.treeWidgetPluginList.currentItem().text(0))
    lines = ''
    for line in self.pluginsDict[pluginName]:
      lines = lines + line + '\n'
    self.ui.textBrowserPlugin.setText(lines)

      	
#####################
#Other methodsprint
#####################

  def findPlugins(self):
    bukkitDir = os.path.split(self.s.startupScript)[0]
    pluginsDir = os.path.join(bukkitDir, 'plugins')
    pluginsListRaw = os.listdir(pluginsDir)
    for plugin in pluginsListRaw: #Dont include it twice if there is a .jar and a folder with the same name
      pluginName = plugin.split('.')[0]
      if pluginName not in self.pluginsDict:
        self.pluginsDict[pluginName] = []
    self.updatePluginsList()
    

  def getNewServerLines(self):
    if self.lastServerLine == 'first run': #If we are first starting up the app, read back to the last reboot
      newServerLines = self.s.consoleReadTo(' [INFO] Stopping server')
    else:
      newServerLines = self.s.consoleReadTo(self.lastServerLine)
    if len(newServerLines) > 0:
      self.lastServerLine = newServerLines[-1]
    return newServerLines
    
  def routeServerLines(self):
  
    #Set up variables to monitor if we found any of the relevent lines. We do this so we dont have
    #to call their respective functions of nothing was found
    chatLinesWereFound = False
    playersChanged = False
    
    newServerLines = self.getNewServerLines()
    chatLines = []
    if len(newServerLines) > 0: #Don't waste your time if no new lines are found
      for line in newServerLines:
        matchChat = re.search(r'<\w+>', line)
        matchChat2 = re.search(r'\[CONSOLE\]', line)
        matchLoggedIn = re.search(r'(\d+\-\d+\-\d+ \d+:\d+:\d+) \[INFO\] (\w+) \[/(\d+\.\d+\.\d+\.\d+:\d+)\] logged in with entity id (\d+) at', line)
        matchLoggedOut = re.search(r'\] (\w+) lost connection: disconnect.quitting', line)
        matchLoggedOut2 = re.search(r'\] (\w+) lost connection: disconnect.endOfStream', line)
        matchPlugin = re.search(r'\d+\-\d+\-\d+ \d+:\d+:\d+ \[INFO\] \[(\w+)\]', line)
 
        if matchChat or matchChat2:
          chatLinesWereFound = True
          chatLines.append(line)
        
        if matchLoggedIn:
          playersChanged = True
          time = matchLoggedIn.group(1)
          name = matchLoggedIn.group(2)
          ip = matchLoggedIn.group(3)
          ID = matchLoggedIn.group(4)
          self.onlineDict[name] = {'Logged In':time[11:],
                                   'IP':ip,
                                   'ID':ID}
        
        if matchLoggedOut or matchLoggedOut2:
          playersChanged = True
          try:
            name = matchLoggedOut.group(1)
          except AttributeError:
            name = matchLoggedOut2.group(1)
          if name in self.onlineDict:
            del self.onlineDict[name]
            
        if matchPlugin:
          pluginName = matchPlugin.group(1)
          if pluginName in self.pluginsDict:
            self.pluginsDict[pluginName].append(line)
            
            
      self.updateConsoleDisplay(newServerLines)
      if chatLinesWereFound: self.updateChatDisplay(chatLines)
      if playersChanged: self.updatePlayersDisplay()
    return None
   
  def ticToc(self):
    self.updateStatusBar()
    self.routeServerLines()
  
  def startRepeatingTimer(self):
    self.repeatingTimer.start(1000)
  
  def updateStatusBar(self):
    if self.s.status():
      line = 'SERVER IS ON - Players Online: ' + str(len(self.onlineDict))
    else:
      line = 'SERVER IS OFF'
    self.ui.statusbar.showMessage(line)
Exemplo n.º 39
0
 def __init__(self, parent=None):
   QtGui.QWidget.__init__(self)
   self.ui = Ui_MainWindow()
   self.ui.setupUi(self)
   self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
   self.initUI()
Exemplo n.º 40
0
class TimerWindow(QMainWindow):

	def __init__(self, path):
		super(TimerWindow, self).__init__()
		self.initUI()
		self.path = path
		self.timerState = TimerappStates["Reset"]
		#print "TimerState: ", self.timerState
		self.systemTrayIcon = QSystemTrayIcon(QIcon(self.path + "bomb.png"), self)			# TODO: use absolute path
		self.setup_menu()
		self.systemTrayIcon.activated.connect(self.on_systemTrayIcon_activated)
		self.systemTrayIcon.show()
		self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
		self.setup_logic()
		QApplication.setQuitOnLastWindowClosed(False)
		
	def closeEvent(self, event):
		# do stuff
		can_exit = True
		if can_exit:
			event.accept() # let the window close
		else:
			event.ignore()

	def setup_menu(self):
		self.traymenu = QMenu(self)
		self.combineAction = self.traymenu.addAction("Start")
		self.combineAction.triggered.connect(self.toggle_combined)
		self.combineAction.setVisible(False)
		self.showAction = self.traymenu.addAction("Show")
		self.showAction.triggered.connect(self.toggleShowWindow)
		self.traymenu.addSeparator()
		self.quitAction = self.traymenu.addAction("Quit")
		self.quitAction.triggered.connect(qApp.quit);
		self.systemTrayIcon.setContextMenu(self.traymenu)
		
	def setup_logic(self):
		self.FirstBtnStates = ("Start", "Pause", "Continue")
		self.ui.pushButton.setText(self.FirstBtnStates[0])
		self.ui.pushButton.setEnabled(False)
		self.info_timeout = 0;	# timeout information in seconds
		self.init_timeout = 0;	# initial timer value in seconds
		self.ui.lineEdit.textChanged.connect(self.on_text_edit_changed)
		self.ui.lineEdit.returnPressed.connect(self.on_return_pressed)
		self.ui.lineEdit.setValidator(QRegExpValidator(QtCore.QRegExp("[0-9]+")))
		self.ui.pushButton.clicked.connect(self.on_start_btn_pressed)
		self.ui.pushButton_2.clicked.connect(self.on_reset_timer)
		self.infoTimer = QtCore.QTimer(self)
		self.infoTimer.timeout.connect(self.on_info_timeout)
		self.systemTrayIcon.setToolTip(AppVersion)

	@QtCore.pyqtSlot(QSystemTrayIcon.ActivationReason)
	def on_systemTrayIcon_activated(self, reason):
		if reason == QSystemTrayIcon.DoubleClick:
			if self.isShown:
				self.showAction.setText("Show")
				self.hide()
				self.isShown = False
			else:
				self.showAction.setText("Hide")
				self.showNormal()
				self.activateWindow()
				self.isShown = True

	def on_text_edit_changed(self, text):
		#print ("Input %s" % text)
		if len(text) == 0:
			self.info_timeout = 0
			self.ui.pushButton.setEnabled(False)
		else:
			self.info_timeout = int(text) * 60
			self.ui.lcdNumber.display(self.info_timeout) #display timeout in seconds
			if self.info_timeout > 0:
				self.ui.pushButton.setEnabled(True)
				self.init_timeout = self.info_timeout

	def on_return_pressed(self):
		#print ("on_return_pressed")
		self.on_start_btn_pressed(self)

			
	def start_timer(self):
		self.infoTimer.start(1000) # 1 sec duration
		self.ui.pushButton.setText(self.FirstBtnStates[1])
		self.systemTrayIcon.setIcon(QIcon(self.path + "bomb_run.png"))
		self.ui.lineEdit.setReadOnly(True)
		self.timerState = TimerappStates["Run"]
		self.combineAction.setText("Pause")
		self.combineAction.setVisible(True)
		
	def pause_timer(self):
		self.infoTimer.stop()
		self.ui.pushButton.setText(self.FirstBtnStates[2])
		self.systemTrayIcon.setIcon(QIcon(self.path + "bomb_paused.png"))
		self.systemTrayIcon.setToolTip("[Paused|%s" % (self.calc_time_info()))
		self.timerState = TimerappStates["Pause"]
		self.combineAction.setText("Resume")
		
	def continue_timer(self):
		self.infoTimer.start(1000)
		self.ui.pushButton.setText(self.FirstBtnStates[1])
		self.systemTrayIcon.setIcon(QIcon(self.path + "bomb_run.png"))
		self.combineAction.setText("Pause")
		self.timerState = TimerappStates["Run"]	

	def on_start_btn_pressed(self, triggered):
		if self.timerState == TimerappStates["Reset"]:		# Start timer
			self.start_timer()
		elif self.timerState == TimerappStates["Run"]: 		# Pause timer
			self.pause_timer()
		else: 												# Continue timer
			self.continue_timer()
			
	def reset_timer(self):
		self.timerState = TimerappStates["Reset"]
		self.ui.pushButton.setText(self.FirstBtnStates[0])
		self.infoTimer.stop()
		self.info_timeout = 0
		self.ui.lineEdit.setText("")
		self.ui.lcdNumber.display(self.info_timeout)
		self.systemTrayIcon.setIcon(QIcon(self.path + "bomb.png"))
		self.systemTrayIcon.setToolTip(AppVersion)
		self.ui.lineEdit.setReadOnly(False)
		self.combineAction.setVisible(False)

	def on_reset_timer(self, triggered):
		self.reset_timer()

	def on_timeout(self):
		self.systemTrayIcon.setToolTip("TImeout")
		self.reset_timer()
		msgBox = QMessageBox(QMessageBox.Information,
			"== Notification ==",
			"On timer!",
			QMessageBox.NoButton,
			None)
		screenrect = QDesktopWidget().screen().rect()
		msgBox.move(QPoint(screenrect.width() / 2 - msgBox.sizeHint().width() / 2,
			screenrect.height() / 2 - msgBox.sizeHint().height() / 2))
		msgBox.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
		msgBox.exec_()
		
	def calc_time_info(self):
		# if timeout less than 5 minutes then show seconds else show minutes
		result = "[%d min|" % (self.init_timeout / 60)
		if self.info_timeout < 300:
			result += ("|left %d sec]" % self.info_timeout)
		else:
			result += ("|left %d min]" % (self.info_timeout / 60))
		return result
			
	def on_info_timeout(self):
		self.info_timeout -= 1
		self.ui.lcdNumber.display(self.info_timeout)
		self.systemTrayIcon.setToolTip(self.calc_time_info())
		if 0 == self.info_timeout:
			self.on_timeout()

	def changeEvent(self, event):
		if event.type() == QtCore.QEvent.WindowStateChange:
			if self.windowState() & QtCore.Qt.WindowMinimized:
				QtCore.QTimer.singleShot(0, self, QtCore.SLOT("hide()"))
				self.showAction.setText("Show")
				self.isShown = False
		QMainWindow.changeEvent(self, event)

	def initUI(self):
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		exitAction = QAction(QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(qApp.quit)
		self.statusBar()
		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(exitAction)
		self.setWindowTitle('Timer')
		self.isShown = False

	def toggleShowWindow(self):
		self.isShown = not self.isShown
		item = QObject.sender(self)
		if self.isShown:
			item.setText("Hide")
			self.activateWindow()
			self.showNormal()
		else:
			item.setText("Show")
			self.hide()
			
	def toggle_combined(self):
		if self.timerState == TimerappStates["Run"]: 		# Pause timer
			self.pause_timer()
		elif self.timerState == TimerappStates["Pause"]:	# Continue timer
			self.continue_timer()
Exemplo n.º 41
0
class StartQT4(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Exemplo n.º 42
0
Arquivo: 1.py Projeto: Red82/pyQT
class MyCalc(QtGui.QMainWindow):
#Instance Vars
    lcdString = '' #Stores string for lcd display
    operation = '' #Current operation
    currentNum = 0
    previousNum = 0
    ans = 0


    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUI()

    def initUI(self):
        #Connect Num Buttons
        self.connect(self.ui.b1, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b2, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b3, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b4, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b5, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b6, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b7, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b8, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b9, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.b0, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        self.connect(self.ui.period, QtCore.SIGNAL('clicked()'), self.buttonClicked)

        #Connect Clr
        self.connect(self.ui.clr, QtCore.SIGNAL('clicked()'), self.clrClicked)

        #Connect Op buttons
        self.connect(self.ui.plus, QtCore.SIGNAL('clicked()'), self.opClicked)
        self.connect(self.ui.minus, QtCore.SIGNAL('clicked()'), self.opClicked)
        self.connect(self.ui.multiply, QtCore.SIGNAL('clicked()'), self.opClicked)
        self.connect(self.ui.divide, QtCore.SIGNAL('clicked()'), self.opClicked)

        #Connect Enter
        self.connect(self.ui.enter, QtCore.SIGNAL('clicked()'), self.enterClicked)

    def buttonClicked(self):
        self.lcdString = self.lcdString + self.sender().text()
        self.ui.lcd.display(self.lcdString)
        self.currentNum = float(self.lcdString)

    def clrClicked(self):
        #update vars
        self.lcdString = ''
        self.currentNum = 0
        self.previousNum = 0
        #update display
        self.ui.lcd.display(0)

    def opClicked(self):
        self.previousNum = self.currentNum
        self.currentNum = 0
        self.lcdString = ''
        self.operation = self.sender().objectName()

    def enterClicked(self):
        if self.operation == 'plus':
            self.ans = self.previousNum + self.currentNum

        if self.operation == 'minus':
            self.ans = self.previousNum - self.currentNum

        if self.operation == 'multiply':
            self.ans = self.previousNum * self.currentNum

        if self.operation == 'divide':
            self.ans = self.previousNum / self.currentNum

        self.currentNum = self.ans
        self.ui.lcd.display(self.ans)
        self.lcdString = ''
Exemplo n.º 43
0
class ControlMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(ControlMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.settings = QSettings('Classificador', 'Independente')
        self._prepare_settings()
        self._abrir_pasta(self.settings.value('pasta_imagens'))
        # Caminho da pasta com as configurações de parâmetro.
        self.pasta_settings = os.path.join(self.settings.value('pasta_imagens'), 'images_settings')

    def _prepare_settings(self):
        # Verifica se tem o dir de imagens
        if not self.settings.contains('pasta_imagens'):
            self.settings.setValue('pasta_imagens', '.')

    def _inicio_selecao(self):
        print ("oi")


    def show_image(self, cv_image, destination='imagem_original'):
        """Show image on the interface.

        :param np.ndarray cv_image: OpenCV image (numpy array).
        :param destination: Name of QLabel to display the image.
        """
        # Muda a ordem das cores
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)

        # Alpha ou não.
        alpha = False
        formato = QImage.Format_ARGB32 if alpha else QImage.Format_RGB888

        # Caso  para mostrar a cv_image lida do disco, strides é necessaorio ou fica distorcida.
        # Strides é mais ou menos os espaços na memória entres as bandas.
        qimage = QImage(cv_image, cv_image.shape[1], cv_image.shape[0], cv_image.strides[0], formato)
        qpixmap = QPixmap.fromImage(qimage)
        imagem_widget = self.ui.centralwidget.findChild(QLabel, destination)
        imagem_widget.setPixmap(qpixmap)

    def _abrir_pasta(self, pasta):
        self.ui.caminho_pasta_imagens.setText(pasta)
        self.pasta = pasta
        #Lista os arquivos jpg.
        arquivos = os.listdir(pasta)
        arquivos_imagens = []
        for arquivo in arquivos:
            print os.path.splitext(arquivo)[1]
            if os.path.splitext(arquivo)[1] in ('.jpg', '.JPG', '.png', '.PNG'):
                arquivos_imagens.append(arquivo)
        self.ui.files_list.clear()
        self.ui.files_list.insertItems(0, arquivos_imagens)

    def selecionar_pasta(self):
        pasta = QFileDialog.getExistingDirectory(self, caption="Selecione uma pasta.")
        self.settings.setValue('pasta_imagens', pasta)
        # Caminho da pasta com as configurações de parâmetro.
        self.pasta_settings = os.path.join(self.settings.value('pasta_imagens'), 'images_settings')
        self._abrir_pasta(pasta)

    def selecionar_imagem(self):
        item = self.ui.files_list.currentItem()
        arquivo_imagem = os.path.join(self.pasta, item.text())
        imagem_settings = ImagemSettings(item.text(), self.pasta_settings)

        self.image_handler = ImageHandler(arquivo_imagem, imagem_settings)

        # Disponibiliza a imagem HSV no widget
        self.ui.imagem_original.cv_image = self.image_handler.hsv_image
        self.alterar_interface()


        self.show_image(self.image_handler.cv_image)
        self.show_image(self.image_handler.classificar_imagem(), destination='imagem_classificada')

    def alterar_interface(self):
        parametro = 'verde_upper'
        self.ui.hsv_h.setValue(self.image_handler.imagem_settings.param[parametro][0])
        self.ui.hsv_s.setValue(self.image_handler.imagem_settings.param[parametro][1])
        self.ui.hsv_v.setValue(self.image_handler.imagem_settings.param[parametro][2])
        parametro = 'verde_lower'
        self.ui.hsv_h_2.setValue(self.image_handler.imagem_settings.param[parametro][0])
        self.ui.hsv_s_2.setValue(self.image_handler.imagem_settings.param[parametro][1])
        self.ui.hsv_v_2.setValue(self.image_handler.imagem_settings.param[parametro][2])
        parametro = 'palha_upper'
        self.ui.hsv_h_3.setValue(self.image_handler.imagem_settings.param[parametro][0])
        self.ui.hsv_s_3.setValue(self.image_handler.imagem_settings.param[parametro][1])
        self.ui.hsv_v_3.setValue(self.image_handler.imagem_settings.param[parametro][2])
        parametro = 'palha_lower'
        self.ui.hsv_h_4.setValue(self.image_handler.imagem_settings.param[parametro][0])
        self.ui.hsv_s_4.setValue(self.image_handler.imagem_settings.param[parametro][1])
        self.ui.hsv_v_4.setValue(self.image_handler.imagem_settings.param[parametro][2])

    def alterar_parametro(self):
        # Pega os parametros.
        # Verde.
        parametro = 'verde_upper'
        h, s, v = self.ui.hsv_h.value(), self.ui.hsv_s.value(), self.ui.hsv_v.value()
        self.image_handler.imagem_settings.param[parametro] = [h, s, v]
        parametro = 'verde_lower'
        h, s, v = self.ui.hsv_h_2.value(), self.ui.hsv_s_2.value(), self.ui.hsv_v_2.value()
        self.image_handler.imagem_settings.param[parametro] = [h, s, v]
        self.image_handler.imagem_settings.salvar()

        # Palha.
        parametro = 'palha_upper'
        h, s, v = self.ui.hsv_h_3.value(), self.ui.hsv_s_3.value(), self.ui.hsv_v_3.value()
        self.image_handler.imagem_settings.param[parametro] = [h, s, v]
        parametro = 'palha_lower'
        h, s, v = self.ui.hsv_h_4.value(), self.ui.hsv_s_4.value(), self.ui.hsv_v_4.value()
        self.image_handler.imagem_settings.param[parametro] = [h, s, v]

        #Salva.
        self.image_handler.imagem_settings.salvar()

        #Recalcula.
        self.show_image(self.image_handler.classificar_imagem(), destination='imagem_classificada')
Exemplo n.º 44
0
class MonAppli(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ecopainter = QtGui.QPainter()
        self.trois_D = False
        self.nb_iter = 0
        self.fraction = 0.5
        self.puiss = 1
        self.terrain = None
        self.figure2D = self.figure3D = Figure() #figsize=(width, height), dpi=dpi
        self.cours_eau = None

        # Configuration de l'interface utilisateur.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.actionQuitter, QtCore.SIGNAL("triggered()"), self.quit)
        QtCore.QObject.connect(self.ui.Iterations,QtCore.SIGNAL("valueChanged(int)"), self.nbIter)
        self.ui.bruit_lin.toggled.connect(self.bruitLin)
        self.ui.bruit_quadra.toggled.connect(self.bruitQua)
        self.ui.bruit_racine.toggled.connect(self.bruitRac)
        QtCore.QObject.connect(self.ui.val_fraction,QtCore.SIGNAL("valueChanged(double)"),self.frac)
        self.ui.deuxD.toggled.connect(self.deuxDim)
        self.ui.troisD.toggled.connect(self.troisDim)
        QtCore.QObject.connect(self.ui.generer_bouton,QtCore.SIGNAL("clicked()"),self.generer)

        QtCore.QObject.connect(self.ui.val_fraction, QtCore.SIGNAL("valueChanged(double)"), self.change_val_doubleSpin)
        QtCore.QObject.connect(self.ui.Fraction, QtCore.SIGNAL("valueChanged(int)"), self.change_position_slider)

        QtCore.QObject.connect(self.ui.ajouter_cours_bouton,QtCore.SIGNAL("clicked()"),self.ajoute_cours)


    def change_position_slider(self, path):
        self.ui.val_fraction.setValue(path/100)

    def change_val_doubleSpin(self, path):
        self.ui.Fraction.setSliderPosition(path*100)

    def nbIter(self, path):
        self.nb_iter = path

    def bruitLin(self):
        self.puiss = 1

    def bruitQua(self):
        self.puiss = 2

    def bruitRac(self):
        self.puiss = 1/2.

    def frac(self, path):
        self.fraction = path

    def deuxDim(self, path):
        if path:
            self.trois_D = False
        else:
            self.trois_D = True


    def troisDim(self):
        pass

    def ajoute_cours(self):
        if self.terrain is None :
            pass
        else :
            self.terrain.ajoute_cours_eau()
            cours = self.terrain.cours_eau[-1].points
            for i in range(len(cours)):
                cours[i] = (cours[i].x, cours[i].y)
            X, Y = array(cours).T
            self.ui.matplotlib.axes.plot(X,Y,'b-', linewidth=2.0)
            self.ui.matplotlib.draw()


    def generer(self):
        if self.trois_D :
            p1 = Point(0,0,0)
            p2 = Point(1,0,0)
            p3 = Point(1,1,0)
            p4 = Point(0,1,0)
            base = Facette([p1, p2, p3, p4])
            self.terrain = Paysage(base)
        else :
            p1 = Point(0,0)
            p2 = Point(1,0)
            base = Facette([p1, p2])
            self.terrain = Paysage(base)


        for i in range(self.nb_iter):
            self.terrain.itere(self.puiss, self.fraction)

        X, Y, Z = trace(self.terrain)

        self.ui.matplotlib.axes.clear()

        if len(Z) < 1 : #2D
            self.axes2D = self.figure2D.add_subplot(111)
            self.ui.matplotlib.axes.plot(X,Y,'r-')
            self.ui.matplotlib.axes.hold(True)
            self.ui.matplotlib.draw()
        else : #3D
            self.axes2D = None
            self.axes3D = self.figure3D.gca(projection='3d') #self.axes = self.figure.add_subplot(111, projection='3d')
            self.axes3D.set_axis_off()
            self.axes3D.plot_surface(X, Y, Z, cmap=cm.ocean) #ou terrain
            show()
            self.ui.matplotlib.draw()



    def quit(self):
        exit(0)
Exemplo n.º 45
0
class DeathRay(QtGui.QMainWindow):
  '''
  Main application class that contains the GUI control and helper methods.
  '''

  def __init__(self, parent=None):
    QtGui.QWidget.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.initUI()
    
  def initUI(self):
    #Connect the signals and slots
    self.connect(self.ui.actionOpen, QtCore.SIGNAL('triggered()'), self.openFiles)
    self.connect(self.ui.actionOne_Plot, QtCore.SIGNAL('triggered()'), lambda: self.setPlotNumber(1))
    self.connect(self.ui.actionTwo_Plots, QtCore.SIGNAL('triggered()'), lambda: self.setPlotNumber(2)) 
    self.connect(self.ui.actionThree_Plots, QtCore.SIGNAL('triggered()'), lambda: self.setPlotNumber(3)) 
    self.connect(self.ui.actionFour_Plots, QtCore.SIGNAL('triggered()'), lambda: self.setPlotNumber(4))
    self.connect(self.ui.treeRun, QtCore.SIGNAL('itemSelectionChanged()'), self.runClicked)

    #Set initial sizes
    self.ui.splitter.setSizes([150, 500, 150])
    
    self.ui.qwtPlot_2.setHidden(True)
    self.ui.qwtPlot_3.setHidden(True)
    self.ui.qwtPlot_4.setHidden(True)

    #jump to this method while developing
    self.openFiles()

  def openFiles(self):
    '''
    This displays the open file dialog, feeds the selected files to the processor, and
    then plots the results
    '''
    fname = QtGui.QFileDialog.getOpenFileNames(self, 'Select FPGA Output File(s)',
        '/Users/jack/Documents/Senior Year/Senior Design/data/raw')
    self.filesList = [str(x) for x in list(fname)]
    self.Experiment = FileProcessor(self.filesList)
    #pp=pprint.PrettyPrinter()
    #pp.pprint(self.Experiment.processedData)
    self.updateRunDisplay()

    #Plot some stuffs
    self.plotHistogram(self.ui.qwtPlot_1, 0)
    self.plotLine(self.ui.qwtPlot_2, 0, 'scatter')
    self.plotHeatMap(self.ui.qwtPlot_3, 0)
    self.plotLine(self.ui.qwtPlot_4, 0, 'step')

 
  def plotHistogram(self, plot, runIndex):
    '''
    This method displays a histogram using data from .processedData
    '''

    #if there is currently a histogram attached, remove it
    try:
      self.histogram.detach()
    except AttributeError:
      pass

    self.histogram = HistogramItem()
    self.histogram.setColor(Qt.Qt.darkGreen)


    try:
      maxBinValue = max(self.Experiment.processedData[runIndex]['pulsewidthList'])
    except ValueError:
      maxBinValue = 0
    #Add 1 so maxBinValue is included in the array
    binValue = np.arange(0,maxBinValue+1, 30)
    binCounts = np.zeros(len(binValue))
    for pulsewidth in self.Experiment.processedData[runIndex]['pulsewidthList']:
      binCounts[int(pulsewidth/30)] += 1


    numBins = len(binCounts)
    intervals = []
    binNumber = Qwt.QwtArrayDouble(numBins)

    pos = 0.0
    for i in range(numBins):
      width = 30
      binNumber[i] = binCounts[i]
      if pos > 0:
        intervals.append(Qwt.QwtDoubleInterval(pos-15, pos+width-15));
      else:
        intervals.append(Qwt.QwtDoubleInterval(pos, pos+width-15));
      pos += width

    self.histogram.setData(Qwt.QwtIntervalData(intervals, binNumber))
    self.histogram.attach(self.ui.qwtPlot_1)

    plot.setAxisScale(Qwt.QwtPlot.yLeft, 0.0, max(binNumber))
    plot.setAxisScale(Qwt.QwtPlot.xBottom, 0.0, pos, 30)
    plot.setAxisTitle(Qwt.QwtPlot.xBottom, self.Experiment.xAxis)
    plot.setAxisTitle(Qwt.QwtPlot.yLeft, self.Experiment.yAxis)
    plot.setTitle(self.Experiment.plotTitle)
    plot.replot()
    plot.show()

  def plotLine(self, plot, runIndex, curveType):

    x = np.arange(0,3,.1)
    y = x*np.random.rand(30)

    grid = Qwt.QwtPlotGrid()
    grid.setPen(Qt.QPen(Qt.Qt.gray, 0, Qt.Qt.DotLine))
    grid.attach(plot)

    curve = Qwt.QwtPlotCurve()
    curve.setPen(Qt.QPen(Qt.Qt.red))
    curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
    curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse,
                                      Qt.QBrush(),
                                      Qt.QPen(Qt.Qt.black),
                                      Qt.QSize(5, 5)))
    if curveType == 'spline':
      curve.setCurveAttribute(Qwt.QwtPlotCurve.Fitted)

    if curveType == 'step':
      curve.setStyle(Qwt.QwtPlotCurve.Steps)

    if curveType == 'scatter':
      curve.setStyle(Qwt.QwtPlotCurve.NoCurve)
      curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Cross,
                                      Qt.QBrush(),
                                      Qt.QPen(Qt.Qt.red),
                                      Qt.QSize(5, 5)))
    curve.setData(x,y)
    curve.attach(plot)

    self.zoomer = Qwt.QwtPlotZoomer(Qwt.QwtPlot.xBottom,
                                        Qwt.QwtPlot.yLeft,
                                        Qwt.QwtPicker.DragSelection,
                                        Qwt.QwtPicker.AlwaysOff,
                                        plot.canvas())
    self.zoomer.setRubberBandPen(Qt.QPen(Qt.Qt.green))
    plot.replot()


  def plotHeatMap(self, plot, runIndex):
    plotImage = ImagePlot('Heatmap')
    plotImage.attach(plot)
    plotImage.setData(square(512, -2*np.pi, 2*np.pi), (-2*np.pi, 2*np.pi), (-2*np.pi, 2*np.pi))
    
    self.zoomer = Qwt.QwtPlotZoomer(Qwt.QwtPlot.xBottom,
                                        Qwt.QwtPlot.yLeft,
                                        Qwt.QwtPicker.DragSelection,
                                        Qwt.QwtPicker.AlwaysOff,
                                        plot.canvas())
    self.zoomer.setRubberBandPen(Qt.QPen(Qt.Qt.green))




  ####################
  #GUI Control Methods
  ####################

  def updateRunDisplay(self):
    '''
    This method updates the display widget to show a list of all the runs of the
    current experiment.
    
    The data in FileProcessor.displayData is used for the treeWidget
    '''

    self.ui.treeRun.clear()

    for run in self.Experiment.displayData:
      treeItem = QtGui.QTreeWidgetItem(self.ui.treeRun)
      treeItem.setText(0, run[0])

      for subItemIndex in range(len(run)-1):
        child = QtGui.QTreeWidgetItem(treeItem)
        child.setText(0, run[subItemIndex+1])
        treeItem.insertChild(0, child)
        child.setDisabled(True)
      
    #Set 'All Runs' as the selected item
    allRunsItem = self.ui.treeRun.findItems('All Runs',QtCore.Qt.MatchExactly)[0]
    self.ui.treeRun.setItemSelected(allRunsItem, True)

  def updateDataTable(self, index):
    '''
    This method updates the table widget with the data stored in FileProcessor.tableData
    '''
    currentTableData = self.Experiment.tableData[index]
    self.ui.tableWidgetData.clear()
    self.ui.tableWidgetData.setRowCount(max(len(x) for x in currentTableData))
    self.ui.tableWidgetData.setColumnCount(len(currentTableData[0]))
    self.ui.tableWidgetData.setHorizontalHeaderLabels(currentTableData[0])
    for c in range(len(currentTableData)-1):
      for r in range(len(currentTableData[c+1])):
        print c, ',', r
        tableItem = QtGui.QTableWidgetItem(str(currentTableData[c+1][r]))
        tableItem.setTextAlignment(2)
        self.ui.tableWidgetData.setItem(r, c, tableItem)
      self.ui.tableWidgetData.resizeColumnToContents(c)
    #self.ui.tableWidgetData.setSortingEnabled(True)


  def runClicked(self):
    index = self.ui.treeRun.indexFromItem(self.ui.treeRun.selectedItems()[0]).row()
    self.plotHistogram(self.ui.qwtPlot_1, index)
    self.updateDataTable(index)

  def setPlotNumber(self, number):
    self.ui.qwtPlot_1.setVisible(number > 0)
    self.ui.qwtPlot_2.setVisible(number > 1)
    self.ui.qwtPlot_3.setVisible(number > 2)
    self.ui.qwtPlot_4.setVisible(number > 3)
Exemplo n.º 46
0
class MyServer(QtGui.QMainWindow):
  
  def __init__(self, parent=None):
  
    #Instance variables
    self.chatLines = []
    self.consoleLines = []
    self.lastServerLine = ''
    
    #Initialize a QTimer to run background updates (online players, status, new chat messages, etc)
    self.repeatingTimer = QtCore.QTimer()
    self.singleTimer = QtCore.QTimer()
    
    self.s=Server()
    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.initUI()
    
    self.startRepeatingTimer()
    self.sendMessageClicked()
    self.consoleClicked()
    self.onlineClicked()
    

    
    
  def initUI(self):
    self.connect(self.ui.pushButtonStart, QtCore.SIGNAL('clicked()'), self.startClicked)
    self.connect(self.ui.pushButtonStop, QtCore.SIGNAL('clicked()'), self.stopClicked)
    self.connect(self.ui.pushButtonStopStart, QtCore.SIGNAL('clicked()'), self.stopStartClicked)
    
    
    self.connect(self.ui.pushButtonStatus, QtCore.SIGNAL('clicked()'), self.statusClicked)
    self.connect(self.ui.pushButtonOnline, QtCore.SIGNAL('clicked()'), self.onlineClicked)
    
    self.connect(self.ui.pushButtonSendMessage, QtCore.SIGNAL('clicked()'), self.sendMessageClicked)
    self.connect(self.ui.lineEditMessage, QtCore.SIGNAL('returnPressed()'), self.sendMessageClicked)
    
    self.connect(self.ui.pushButtonConsole, QtCore.SIGNAL('clicked()'), self.consoleClicked)
    self.connect(self.ui.lineEditConsole, QtCore.SIGNAL('returnPressed()'), self.consoleClicked)
    
    #Connect the timer button
    self.connect(self.ui.pushButtonStartTimer, QtCore.SIGNAL('clicked()'), self.startRepeatingTimer)
    #Connect the timer
    self.connect(self.repeatingTimer, QtCore.SIGNAL('timeout()'), self.ticToc)
    
  def startClicked(self):
    self.s.start()
    self.checkStatus()
    
  def stopClicked(self):
    self.s.stop()
    self.checkStatus()
    
  def statusClicked(self):
    self.checkStatus()
    
  def onlineClicked(self):
    self.players = self.s.players()
    playersFormatted = ''
    if self.players == ['']:
      playersFormatted = 'No one online. Click to refresh'
    elif len(self.players) is 1 and self.players[0] != '':
      playersFormatted = self.players[0]
    else:
      for player in self.players:
        playersFormatted = playersFormatted + ' ' + player
    self.ui.labelOnline.setText(playersFormatted)
    
  def sendMessageClicked(self):

    message = self.ui.lineEditMessage.text()
    self.ui.lineEditMessage.clear()   
    if message != '':
      self.s.message(message)

    if len(self.chatLines) is 0:
      self.chatLines = self.s.chat(60)
      newChatLines = self.chatLines
    else:
      newChatLine = 'poop'
      searchBack = 0
      while newChatLine not in self.chatLines[-2:]:
        searchBack = searchBack + 1
        newChatLine = self.s.chat(searchBack, oneLine=True)
      newChatLines = self.s.chat(searchBack)
      newChatLines.pop(0)
      
    if len(newChatLines) > 0:
      for line in newChatLines:
        fixedLine = line[5:19] + line[26:]
        width = self.ui.treeWidgetChat.columnWidth(0)
        fixedLine = utils.wordWrap(width-5, fixedLine)
        a = QtGui.QTreeWidgetItem(self.ui.treeWidgetChat)
        a.setText(0, fixedLine)
      self.ui.treeWidgetChat.scrollToItem(a)
    self.chatLines.extend(newChatLines)

      
  def consoleClicked(self):

    message = self.ui.lineEditConsole.text()
    self.ui.lineEditConsole.clear()   
    if message != '':
      self.s.command(message)

    if len(self.consoleLines) is 0:
      self.consoleLines = self.s.console(60)
      newConsoleLines = self.consoleLines
    else:
      newConsoleLine = 'poop'
      searchBack = 0
      while newConsoleLine[0] not in self.consoleLines[-2:]:
        searchBack = searchBack + 1
        newConsoleLine = self.s.console(searchBack, 1)
      newConsoleLines = self.s.console(searchBack)
      newConsoleLines.pop(0)
      
    if len(newConsoleLines) > 0:
      for line in newConsoleLines:
        fixedLine = line[5:19] + line[26:]
        width = self.ui.treeWidgetConsole.columnWidth(0)
        fixedLine = utils.wordWrap(width-5, fixedLine)
        a = QtGui.QTreeWidgetItem(self.ui.treeWidgetConsole)
        a.setText(0, fixedLine)
      self.ui.treeWidgetConsole.scrollToItem(a)
    self.consoleLines.extend(newConsoleLines)
      	
  def stopStartClicked(self):
    if self.s.status():
      self.s.stop()
      self.checkStatus()
      self.ui.pushButtonStopStart.setText('Start Server')
    else:
      self.s.start()    	
      self.checkStatus()
      self.ui.pushButtonStopStart.setText('Stop Server')
      
  def backgroundCheck(self):
    if lastServerLine == '':
      newServerLines = self.s.console(50)
      	
      	
#####################
#Other methods
#####################

  def ticToc(self):
    self.checkStatus()
    self.consoleClicked()
    self.sendMessageClicked()
  
  def startRepeatingTimer(self):
    self.repeatingTimer.start(1000)
  
  def checkStatus(self):
    if self.s.status():
      self.ui.statusbar.showMessage('Server is on')
    else:
      self.ui.statusbar.showMessage('Server is off')
Exemplo n.º 47
0
class MyServer(QtGui.QMainWindow):
  
  def __init__(self, parent=None):
    
    #Are we local or remote?
    self.remote = True

    #Instantiate a minecraft server object
    self.s=Server(remote=self.remote)

    #The usual
    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.initUI()

    #Instance variables
    self.chatLines = []
    self.consoleLines = []
    self.onlineDict = {}
    self.pluginsDict = {} 

       #Set the start/stop button text
    if self.s.status():
      self.ui.pushButtonStopStart.setText('Stop Server')
    else:
      self.ui.pushButtonStopStart.setText('Start Server')

    if self.remote:
      print 'spawning remote thread'
      self.connect(self, QtCore.SIGNAL('newRemoteLines'), self.routeServerLines)
      self.connect(self, QtCore.SIGNAL('pluginsDict'), self.remotePlugins)
      self.thread = GenericThread(self.remoteConn)
      self.thread.start()
      print 'thread started'
    else:
      #Instantiate a qThreadWatcher() to monitor server.log for changes and connect its signal
      #to newLineDetected.
      self.fileWatcher = QtCore.QFileSystemWatcher(self)
      self.fileWatcher.addPath(os.path.join(self.s.bukkitDir, 'server.log'))
      self.connect(self.fileWatcher, QtCore.SIGNAL('fileChanged(QString)'), self.newLineDetected)

      #Find the currently installed plugins by searching the plugin folder
      self.findPlugins()

      #On app boot, read til the last time the server was started
      self.lastServerLine = ' [INFO] Stopping server'
      self.newLineDetected()
     
     #Initialize a QTimer to run and connect it to ticToc
      self.repeatingTimer = QtCore.QTimer()
      self.repeatingTimer.start(1000)      
      self.connect(self.repeatingTimer, QtCore.SIGNAL('timeout()'), self.ticToc)



  def initUI(self):
    #Connect the UI buttons
    self.connect(self.ui.pushButtonStopStart, QtCore.SIGNAL('clicked()'), self.stopStartClicked)
    self.connect(self.ui.lineEditMessage, QtCore.SIGNAL('returnPressed()'), self.sendChat)
    self.connect(self.ui.lineEditConsole, QtCore.SIGNAL('returnPressed()'), self.sendConsole)
    self.connect(self.ui.treeWidgetPluginList, QtCore.SIGNAL('itemSelectionChanged()'), self.pluginNameClicked)

#####################
#GUI control methods
#####################

  #Start or stop the server
  def handleStopStart(self):
    if self.s.status():
      self.s.stop()
      setName = 'Start'
    else:
      self.s.start()
      setName = 'Stop'
    self.emit(QtCore.SIGNAL('stopStartDone(QString)'), setName)

  #This method is called when the stopStart thread (handleStopStart()) has finished
  def stopStartDone(self, setName):
    self.ui.pushButtonStopStart.setEnabled(True)
    self.ui.pushButtonStopStart.setText(setName + ' Server')
    self.updateStatusBar()
    
  #This method spawns a thread to stop or start the server
  def stopStartClicked(self):
    self.ui.pushButtonStopStart.setEnabled(False)
    self.ui.statusbar.showMessage('Trying...')
    self.stopStartThread = GenericThread(self.handleStopStart)
    self.disconnect( self, QtCore.SIGNAL("stopStartDone(QString)"), self.stopStartDone )
    self.connect( self, QtCore.SIGNAL("stopStartDone(QString)"), self.stopStartDone )
    self.stopStartThread.start()

  def updateStatusBar(self):
    if self.s.status():
      line = 'SERVER IS ON - Players Online: ' + str(len(self.onlineDict))
    else:
      line = 'SERVER IS OFF'
    self.ui.statusbar.showMessage(line)

  def sendChat(self):
    message = str(self.ui.lineEditMessage.text())
    self.ui.lineEditMessage.clear()   
    if message != '':
      self.s.message(message)
      print message
    self.updateChatDisplay([])
          
  def updateChatDisplay(self, chatLines): 
    for line in chatLines:
      fixedLine = line[5:19] + line[26:]
      width = self.ui.treeWidgetChat.columnWidth(0)
      fixedLine = utils.wordWrap(width-5, fixedLine)
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetChat)
      a.setText(0, fixedLine)
    if len(chatLines):
      self.ui.treeWidgetChat.scrollToItem(a)
      self.chatLines.extend(chatLines)

  def sendConsole(self):
    message = str(self.ui.lineEditConsole.text())
    self.ui.lineEditConsole.clear()   
    if message != '':
      print message
      self.s.command(message)
    self.updateConsoleDisplay([])
          
  def updateConsoleDisplay(self, consoleLines): 
    for line in consoleLines:
      fixedLine = line[5:19] + line[26:]
      width = self.ui.treeWidgetConsole.columnWidth(0)
      fixedLine = utils.wordWrap(width-5, fixedLine)
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetConsole)
      a.setText(0, fixedLine)
    if len(consoleLines):
      self.ui.treeWidgetConsole.scrollToItem(a)
      self.consoleLines.extend(consoleLines)
  
  def updatePlayersDisplay(self):
    self.ui.treeWidgetPlayersList.clear()
    for name in self.onlineDict:
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetPlayersList)
      a.setText(0, name)
      childrenList = []
      for key in self.onlineDict[name]:
        w = QtGui.QTreeWidgetItem(a)
        w.setText(0, str(key) + ': ' + str(self.onlineDict[name][key]))
        a.insertChild(0, w)
  
  def updatePluginsList(self):
    for pluginName in self.pluginsDict.keys():
      a = QtGui.QTreeWidgetItem(self.ui.treeWidgetPluginList)
      a.setText(0, str(pluginName))
      
  def pluginNameClicked(self):
    pluginName = str(self.ui.treeWidgetPluginList.currentItem().text(0))
    lines = '\n'.join(self.pluginsDict[pluginName])
    self.ui.textBrowserPlugin.setText(lines)

      	
#####################
#Other methods
#####################

  #This function finds all the plugins in the plugins folder and stores them in a dict
  def findPlugins(self):
    bukkitDir = os.path.split(self.s.startupScript)[0]
    pluginsDir = os.path.join(bukkitDir, 'plugins')
    pluginsListRaw = os.listdir(pluginsDir)
    for plugin in pluginsListRaw: #Dont include it twice if there is a .jar and a folder with the same name
      pluginName = plugin.split('.')[0]
      if pluginName not in self.pluginsDict:
        self.pluginsDict[pluginName] = []
    self.updatePluginsList()

  #If the server.log file is changed, a signal connected to this function will be emitted
  def newLineDetected(self):
    thread = GenericThread(self.getNewLines, self.lastServerLine)
    self.disconnect(self, QtCore.SIGNAL('stringFound'), self.routeServerLines)
    self.connect(self, QtCore.SIGNAL('stringFound'), self.routeServerLines)
    thread.start()

  #This function is spawned in the thread to get new lines.
  def getNewLines(self, lastLine):
    newServerLines = self.s.consoleReadTo(lastLine)
    self.emit(QtCore.SIGNAL('stringFound'), newServerLines)

  #This function takes a list of new server lines and routes them to where they need to go.
  def routeServerLines(self, newServerLines):
    chatLines = []
    self.lastServerLine = newServerLines[-1] #Store the last line so we know where to read to later
    for line in newServerLines:
      matchChat = re.search(r'<\w+>', line)
      matchChat2 = re.search(r'\[CONSOLE\]', line)
      matchLoggedIn = re.search(r'(\d+\-\d+\-\d+ \d+:\d+:\d+) \[INFO\] (\w+) \[/(\d+\.\d+\.\d+\.\d+:\d+)\] logged in with entity id (\d+) at', line)
      matchLoggedOut = re.search(r'\] (\w+) lost connection: disconnect.quitting', line)
      matchLoggedOut2 = re.search(r'\] (\w+) lost connection: disconnect.endOfStream', line)
      matchPlugin = re.search(r'\d+\-\d+\-\d+ \d+:\d+:\d+ \[INFO\] \[(\w+)\]', line)

      if matchChat or matchChat2:
        chatLines.append(line)
      
      if matchLoggedIn:
        time = matchLoggedIn.group(1)
        name = matchLoggedIn.group(2)
        ip = matchLoggedIn.group(3)
        ID = matchLoggedIn.group(4)
        self.onlineDict[name] = {'Logged In':time[11:],
                                 'IP':ip,
                                 'ID':ID}
      
      if matchLoggedOut or matchLoggedOut2:
        try:
          name = matchLoggedOut.group(1)
        except AttributeError:
          name = matchLoggedOut2.group(1)
        if name in self.onlineDict:
          del self.onlineDict[name]
          
      if matchPlugin:
        pluginName = matchPlugin.group(1)
        if pluginName in self.pluginsDict:
          self.pluginsDict[pluginName].append(line)
          
          
    self.updateConsoleDisplay(newServerLines)
    self.updateChatDisplay(chatLines)
    self.updatePlayersDisplay()

  def ticToc(self):
    self.updateStatusBar()

  def remoteConn(self, HOST='jj.ax.lt', PORT=25562):
    import socket, time
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    
    pluginsListRaw = ''
    while '0o9i' not in pluginsListRaw:
      newData = s.recv(2048)
      pluginsListRaw += newData
    pluginsList = pluginsListRaw.split('0o9i')[0].split('\n')
    pluginsDict = {}
    for pluginName in pluginsList:
      pluginsDict[pluginName] = []
    self.emit(QtCore.SIGNAL('pluginsDict'), pluginsDict)
    
    newLinesRaw = pluginsListRaw.split('0o9i')[1]
    while 1:
      newData = s.recv(1024)
      newLinesRaw += newData
      if newLinesRaw[-6:] == ',.4r5t': #This is sent end the end of each transfer
        newLines = newLinesRaw.split('\n')[:-1]
        print '\nNew Lines:\n', newLines
        self.emit(QtCore.SIGNAL('newRemoteLines'), newLines)
        newLinesRaw=''
      else:
        time.sleep(.1)
        self.updateStatusBar() #This isnt working for some reason. Maybe cause its in a thread
    s.close()
    
  def remotePlugins(self, pluginsDict):
    self.pluginsDict = pluginsDict
    self.updatePluginsList()
Exemplo n.º 48
0
 def InterfaceShow(self):
     self.Interface = QtWidgets.QMainWindow()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self.Interface)
     self.Interface.show()
Exemplo n.º 49
0
Arquivo: 1.py Projeto: Red82/pyQT
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.initUI()