Пример #1
0
  def create_table(self, tblType):
      
      data = self.db.get_table_data(tblType)
          
      font = QFont('Veranda', 12, QFont.Bold)
      blk = QPalette()
      blk.setColor(blk.Foreground, Qt.black)      
 
      # Check to make sure the list is there and has data, then we go through it and add data to the table.
      if data:
          self.tblSummary.setRowCount(len(data))
          for i, row in enumerate(data):
              for j, col in enumerate(row):
                  item = QTableWidgetItem(str(col))
                  item.setFont(font)
                  #item.setForeground(QColor.fr
                  #item.setFlags(Qt.ItemIsEditable)
                  if item.text() == "None":
                      item.setText("")
                  self.tblSummary.setItem(i, j, item)      
      else:
          self.tblSummary.setRowCount(1)
          item = QTableWidgetItem()
          item.setText("Nothing Found")
          self.tblSummary.setItem(0, 0, item)
Пример #2
0
 def __init__(self):
     super().__init__()
     
     self.setGeometry(600, 200, 420, 320)
     self.setWindowTitle('Help')
     self.setWindowIcon(QIcon(ICON_PATH))
     
     label = QLabel('Press anything on your keyboard to see what it does.')
     self.actionLabel = QLabel('Press something!')
     self.img = QLabel('img', self)
     self.img.setPixmap(QPixmap(HELP_IMG_PATH))
     
     
     grid = QGridLayout()
     grid.setSpacing(4)
     
     grid.addWidget(self.img, 0, 0)
     grid.addWidget(label, 1, 0)
     grid.addWidget(self.actionLabel, 2, 0)
     
     myFont=QFont()
     myFont.setBold(True)
     myFont.setPixelSize(24)
     self.actionLabel.setFont(myFont)
     
     palette = QPalette()
     palette.setColor(QPalette.Foreground,Qt.green)
     self.actionLabel.setPalette(palette)
     
     self.setLayout(grid)
     self.show()
Пример #3
0
	def setBackGround(self,backColor):
		if self.isSetBackground : return
		palette = QPalette()
		palette.setColor(QPalette.Background,backColor)
		self.setAutoFillBackground(True)
		self.setPalette(palette);
		self.isSetBackground = True
Пример #4
0
 def start_report(self): 
     self.viewQueues.start()
     self.setEnabled(False)
     bgColor = QPalette()
     bgColor.setColor(self.backgroundRole(), Qt.lightGray)
     self.setPalette(bgColor)
     self.myLoadingMovie.show()
Пример #5
0
    def initUI(self):
        """Creates parts of layout that account for sizes.
        Notable is that the boardScene squares will be a multiple of 8."""
        screens = [QDesktopWidget().availableGeometry(i) for i in
                   range(QDesktopWidget().screenCount())]
        assert screens
        maxWidth = max(min(s.width(), s.height()) for s in screens)
        sceneWidth = int(maxWidth / 8) * 8
        self.boardScene.initSquares(sceneWidth / 8)
        self.boardScene.setSceneRect(0, 0, sceneWidth, sceneWidth)
        self.boardSceneView.initUI(sceneWidth)

        """Creates layout without accounting for sizes"""
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background, Qt.green)
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.vertLayout = QVBoxLayout(self)
        self.vertLayout.setSpacing(0)
        self.vertLayout.setContentsMargins(0, 0, 0, 0)
        self.vertLayout.addWidget(self.moveTreeView)
        self.vertLayout.addWidget(self.engineWidget)
        self.vertWidget = QWidget(self)
        self.vertWidget.setLayout(self.vertLayout)
        horiLayout = QHBoxLayout(self)
        horiLayout.setSpacing(0)
        horiLayout.setContentsMargins(0, 0, 0, 0)
        horiLayout.addWidget(self.boardSceneView)
        horiLayout.addWidget(self.vertWidget)
        self.setLayout(horiLayout)
Пример #6
0
 def __init__(self):
     super(AvailableSizes, self).__init__()
     
     self.createCombos()
     self.createHeader()
     #self.createMenuBar()
     
     self.printOut = QTextEdit()
     self.printOut.setFont(QFont('Helvetica', 11, QFont.Bold))
     self.printOut.setReadOnly(True)
     
     mainLayout = QVBoxLayout()
     #mainLayout.setMenuBar(self.menuBar)
     mainLayout.addWidget(self.frmHeader)
     mainLayout.addWidget(self.grpBox)
     mainLayout.addWidget(self.printOut)
     #mainLayout.setAlignment(self.frmHeader, Qt.AlignRight)
     self.setLayout(mainLayout)
     
     #self.setWindowTitle("Available Sizes")
     self.setWindowFlags(Qt.FramelessWindowHint)
     bgColor = QPalette()
     bgColor.setColor(self.backgroundRole(), Qt.gray)
     self.setPalette(bgColor)
     self.setWindowIcon(QIcon('icon/PS_Icon.png'))
     self.cbSku.setFocus()
Пример #7
0
 def __init__(self, parent=None, interval=50):
     QWidget.__init__(self, parent)
     palette = QPalette(self.palette())
     palette.setColor(palette.Background, Qt.transparent)
     self.setPalette(palette)
     self.counter = 0
     self.interval = interval
Пример #8
0
 def updateFilledCircle(self, s):
     size = s * self.zoom
     pixmap = QPixmap(self.width(), self.height())
     pixmap.fill(Qt.transparent)
     #painter filled ellipse
     p = QPalette()
     painter = QPainter()
     painter.begin(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     brush = QBrush(p.link().color())
     painter.setBrush(brush)
     painter.setOpacity(0.4)
     painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter.end()
     #painter ellipse 2
     painter2 = QPainter()
     painter2.begin(pixmap)
     painter2.setRenderHint(QPainter.Antialiasing)
     pen2 = QPen(Qt.green)
     pen2.setWidth(1)
     painter2.setPen(pen2)
     painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size))
     painter2.end()
     
     self.ellipseLabel.setPixmap(QPixmap(pixmap))
     self.lastSize = s
Пример #9
0
    def setup_ui(self):
        self.battleWindow.setWindowTitle(self.battleWindow.config.get_text('battle.window.title') + ' v' + str(self.battleWindow.config.version))
        background = self.battleWindow.config.theme_selected.get_background_pixmap()
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(background))
        self.battleWindow.setMinimumSize(constants.get_min_resolution_qsize())
        self.battleWindow.setAutoFillBackground(True)
        self.gridLayout.setVerticalSpacing(0)

        self.setup_hint_label()  # Labels
        self.setup_turn_label()  # Labels
        self.setup_space()  # Space item

        self.setup_help_button()  # Help Push Button
        self.setup_next_target_button()  # Next Target Button
        self.setup_end_unit_button()  # End Unit Button
        self.setup_retreat_button()  # Retreat Button
        self.setup_auto_combat_button()  # Automatic battle button

        self.setup_targeted_unit_view()  # Targeted Unit view
        self.setup_current_unit_view()  # Current Unit View
        self.setup_coat_of_arms_view()  # Coat of Arm view

        self.setup_map()  # Main view
        self.battleWindow.setPalette(palette)
        self.battleWindow.setCentralWidget(self.centralWidget)

        # noinspection PyArgumentList
        QMetaObject.connectSlotsByName(self.battleWindow)
Пример #10
0
	def init(self):
		self.cpus=multiprocessing.cpu_count()
		
		self.tab.setTabsClosable(True)
		self.tab.setMovable(True)
		self.tab.setTabBar(QHTabBar())
		self.tab.setTabPosition(QTabWidget.West)
		
		self.font = QFont()
		self.font.setFamily('Monospace')
		self.font.setStyleHint(QFont.Monospace)
		self.font.setFixedPitch(True)
		self.font.setPointSize(int(12))

		self.terminals=[]
		self.process=[]
		for i in range(0,self.cpus):
			term=QTextEdit()
			term.setFont(self.font)
			
			pal = QPalette()
			bgc = QColor(0, 0, 0)
			pal.setColor(QPalette.Base, bgc)
			textc = QColor(230, 230, 230)
			pal.setColor(QPalette.Text, textc)
			term.setPalette(pal)

			proc=QProcess(self)
			proc.readyRead.connect(functools.partial(self.dataReady,i))
			self.process.append(proc)
			self.terminals.append(term)
			self.tab.addTab(term,"cpu "+str(i))
Пример #11
0
class RoundedPushButton1(QPushButton):
    def __init__(self,parent, default_wide, default_high,text=''):
        QPushButton.__init__(self, parent)
        #self.resize(100,80)
        self.default_high=default_high
        self.default_wide=default_wide
        self.xrd=self.default_wide/10
        #self.yrd=self.default_high/10
        self.yrd=self.xrd
        #self.resize(self.default_wide,self.default_high)

        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(0)
        self.brush=QBrush(Qt.SolidPattern)

        self.textlabel=textQLabel(self,text)

    def paintEvent(self,event):
        #brush.setStyle(Qt.Dense1Pattern)
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)
        
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawRoundedRect(QRect(0,0,self.default_wide,self.default_high), self.xrd, self.yrd)
        #self.painter.drawPixmap(self.imgx, self.imgy, self.piximg)
        self.painter.end()
Пример #12
0
	def __init__(self, *args, **kwargs):
		super(ImageViewerCenter, self).__init__(*args, **kwargs)
		self.zoomMode = ZOOM_FACTOR
		self.zoomFactor = 1
		self.moving = None

		imgWidget = QLabel()
		imgWidget.setMouseTracking(True)
		imgWidget.setAlignment(Qt.AlignCenter)
		self.setWidget(imgWidget)

		self.setAlignment(Qt.AlignCenter)
		self.setMouseTracking(True)
		self.setFrameShape(self.NoFrame)
		self.setWidgetResizable(True)

		pal = QPalette()
		pal.setColor(QPalette.Window, Qt.black)
		self.setPalette(pal)

		self.leftZone = False
		self.topZone = False

		self.file = None
		self.movie = None
Пример #13
0
    def __init__(self, parent = None):

        QWidget.__init__(self, parent)
        palette = QPalette(self.palette())
        palette.setColor(palette.Background, Qt.transparent)
        self.setPalette(palette)
        self.MINCOUNTER = 10

        self.minloopkeep = False
 def set_faces_color(self, label):
     color = QColorDialog.getColor()
     if color.isValid():
         self.faces_color = color
         label_palette = QPalette()
         label_palette.setColor(QPalette.WindowText, color)
         label.setPalette(label_palette)
         label.setText("Цвет объекта " + color.name())
     self.update()
 def set_pen_color(self, label):
     color = QColorDialog.getColor()
     if color.isValid():
         self.pen = QPen(color, self.pen.width())
         label_palette = QPalette()
         label_palette.setColor(QPalette.WindowText, color)
         label.setPalette(label_palette)
         label.setText("Цвет линии " + color.name())
     self.update()
Пример #16
0
class Monitor(QLabel):
	def __init__(self, parent):
		QLabel.__init__(self, '[ Mon ]', parent)
		self.setAutoFillBackground(True)

	def setColor(self, r, g, b):
		self.palette = QPalette()
		self.palette.setColor(QPalette.Background, QColor(round(r*255), round(g*255), round(b*255)))
		self.setPalette(self.palette)
Пример #17
0
def main():
    app = QApplication(sys.argv)
    palette = QPalette()
    brush = QBrush(QPixmap(imgPath))
    palette.setBrush(QPalette.Window,brush)
    clock = Clock()
    clock.setPalette(palette)


    clock.show()
    sys.exit(app.exec_())
Пример #18
0
    def initUI(self):
        self.viewer_layout = QVBoxLayout()
        horizontal_layout = QHBoxLayout()

        viewer_widget_palette = QPalette()
        viewer_widget_palette.setColor(QPalette.Background, QColor(constants.defaultViewerColor))
        self.setAutoFillBackground(True)
        self.setPalette(viewer_widget_palette)

        horizontal_layout.addLayout(self.viewer_layout)
        self.setLayout(horizontal_layout)
Пример #19
0
 def setColor(self):
     if self.status == BT.FREE:
         color = Qt.red
     elif self.status == BT.ALLOCATED:
         color = Qt.green
     elif self.status == BT.UNALLOCATED:
         color = Qt.black
     pallete = QPalette()
     pallete.setColor(QPalette.Background, color)
     self.setPalette(pallete)
     self.update()
Пример #20
0
def main():
    app = QApplication(sys.argv)
    palette = QPalette()
    brush = QBrush(QPixmap(imgPath))
    palette.setBrush(QPalette.Window,brush)
    clock = Clock()
    clock.setPalette(palette)

 #   clock.setAttribute(Qt.WA_TranslucentBackground)

    clock.show()
    sys.exit(app.exec_())
Пример #21
0
        def __init__(self, image_url):
            super(FigureWidget, self).__init__()

            self.setFixedWidth(600)
            self.setFixedHeight(600)

            box_general = oasysgui.widgetBox(self, "", addSpace=False, orientation="vertical", width=600, height=600)

            gui.separator(box_general, height=30)

            box_top = oasysgui.widgetBox(box_general, "", addSpace=False, orientation="vertical", width=600, height=50)
            title = gui.label(box_top, self, "         Standing Waves plot")

            font = QFont(title.font())
            font.setBold(True)
            font.setPointSize(36)
            palette =  QPalette(title.palette())
            palette.setColor(QPalette.Foreground, QColor('blue'))
            title.setFont(font)
            title.setPalette(palette)

            gui.separator(box_general, height=10)

            box_center = oasysgui.widgetBox(box_general, "", addSpace=False, orientation="horizontal", width=600)

            box_label = oasysgui.widgetBox(box_center, "", addSpace=False, orientation="vertical", width=50)

            oasysgui.widgetBox(box_label, "", addSpace=False, orientation="vertical", height=50)

            label_y_axis = VerticalLabel("Incidence Angle", 200, 50)
            font = QFont(label_y_axis.font())
            font.setBold(True)
            font.setPointSize(24)
            label_y_axis.setFont(font)
            #label_y_axis.setFixedHeight(200)
            #label_y_axis.setFixedWidth(50)

            box_label.layout().addWidget(label_y_axis)

            image_label = QLabel(box_center)
            image = QImage()
            image.loadFromData(HttpManager.send_xray_server_direct_request("/" + image_url, decode=False))
            image_label.setPixmap(QPixmap(image))

            box_center.layout().addWidget(image_label)

            box_bottom = oasysgui.widgetBox(box_general, "", addSpace=False, orientation="horizontal", width=600)
            label_x_axis = gui.label(box_bottom, self, "                                Offset [Å]")
            font = QFont(label_x_axis.font())
            font.setBold(True)
            font.setPointSize(24)
            label_x_axis.setFont(font)
Пример #22
0
    def __init__(self, parent=None):
        super().__init__(parent)
        pal = QPalette()
        pal.setColor(QPalette.Window, QColor("#6a6ea9"))
        pal.setColor(QPalette.WindowText, QColor("white"))
        # self.setFrameStyle(QFrame.Panel | QFrame.Raised)
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self._state = "reload"

        self._layout = QHBoxLayout(self)
        self._message = QLabel("")
        self._layout.addWidget(self._message)
        self._layout.addStretch(1)
Пример #23
0
    def setColor(self):
        """ Separate the current image into cyan, magenta, and yellow
            components.  Create a representation of how each component might
            appear when applied to a blank white piece of paper.
        """
        newColor = QColorDialog.getColor(self.paintColor)

        if newColor.isValid():
            self.paintColor = newColor
            palette = QPalette(self.colorButton.palette())
            palette.setColor(QPalette.Button, self.paintColor)
            self.colorButton.setPalette(palette)
            self.createImage()
            self.imageChanged.emit()
Пример #24
0
    def __init__(self ):  
        super().__init__()
                
        label1 = QLabel(self)
        label2 = QLabel(self)
        label3 = QLabel(self)
        label4 = QLabel(self)
        
        #1
        label1.setText("这是一个文本标签。")
        label1.setAutoFillBackground(True) 
        palette = QPalette()   
        palette.setColor(QPalette.Window,Qt.blue)  
        label1.setPalette(palette) 
        label1.setAlignment( Qt.AlignCenter)
          
        label2.setText("<a href='#'>欢迎使用Python GUI 应用</a>")
        
        label3.setAlignment( Qt.AlignCenter)    
        label3.setToolTip('这是一个图片标签')
        label3.setPixmap( QPixmap("./images/python.jpg"))

        label4.setText("<A href='http://www.cnblogs.com/wangshuo1/'>欢迎访问信平的小屋</a>")
        label4.setAlignment( Qt.AlignRight)
        label4.setToolTip('这是一个超链接标签')
        
        #2
        vbox = QVBoxLayout()
        vbox.addWidget(label1)
        vbox.addStretch()
        vbox.addWidget(label2)
        vbox.addStretch()
        vbox.addWidget( label3 )
        vbox.addStretch()
        vbox.addWidget( label4)
        
        #3
        label1.setOpenExternalLinks(True)
        # 打开允许访问超链接,默认是不允许,需要使用 setOpenExternalLinks(True)允许浏览器访问超链接
        label4.setOpenExternalLinks( False )
        # 点击文本框绑定槽事件  
        label4.linkActivated.connect( link_clicked )
        
        # 划过文本框绑定槽事件       
        label2.linkHovered.connect( link_hovered )
        label1.setTextInteractionFlags( Qt.TextSelectableByMouse )

        self.setLayout(vbox)
        self.setWindowTitle("QLabel 例子")
Пример #25
0
 def _highlightHeaders(self, c, r):       
     p = QPalette()
     for i in range(self.columnCount()):
         col = self.horizontalHeaderItem(i)
         if i == c:
             col.setIconAndTextColor(p.link().color())
         else:
             col.setIconAndTextColor(p.text().color())
         
     for j in range(self.rowCount()):
         row = self.verticalHeaderItem(j)
         if j == r:
             row.setIconAndTextColor(p.link().color())
         else:
             row.setIconAndTextColor(p.text().color())
Пример #26
0
 def __init__(self,parent, text=''):
     QPushButton.__init__(self, parent)
     self.text=text
     self.backgroundColor = QPalette().light().color()
     self.backgroundColor.setRgb(157,157,157) #(220,203,231)
     #self.backgroundColor.setAlpha(0)
     self.brush=QBrush(Qt.SolidPattern)
Пример #27
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_RenamingOptionsPage()
        self.ui.setupUi(self)

        self.ui.ascii_filenames.clicked.connect(self.update_examples)
        self.ui.windows_compatibility.clicked.connect(self.update_examples)
        self.ui.rename_files.clicked.connect(self.update_examples)
        self.ui.move_files.clicked.connect(self.update_examples)
        self.ui.move_files_to.editingFinished.connect(self.update_examples)

        self.ui.move_files.toggled.connect(
            partial(
                enabledSlot,
                self.toggle_file_moving
            )
        )
        self.ui.rename_files.toggled.connect(
            partial(
                enabledSlot,
                self.toggle_file_renaming
            )
        )
        self.ui.file_naming_format.textChanged.connect(self.check_formats)
        self.ui.file_naming_format_default.clicked.connect(self.set_file_naming_format_default)
        self.highlighter = TaggerScriptSyntaxHighlighter(self.ui.file_naming_format.document())
        self.ui.move_files_to_browse.clicked.connect(self.move_files_to_browse)

        textEdit = self.ui.file_naming_format
        self.textEditPaletteNormal = textEdit.palette()
        self.textEditPaletteReadOnly = QPalette(self.textEditPaletteNormal)
        disabled_color = self.textEditPaletteNormal.color(QPalette.Inactive, QPalette.Window)
        self.textEditPaletteReadOnly.setColor(QPalette.Disabled, QPalette.Base, disabled_color)
Пример #28
0
    def __init__(self,parent,wide,high,ppath=None):
        QPushButton.__init__(self,parent)

        self.parent=parent
        self.wide=wide
        self.high=high
        self.resize(self.wide,self.high)
        self.xdis=self.wide/10

        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)

        if ppath :
            self.path=ppath
        else :
            self.path=QPainterPath()

            self.path.moveTo(self.wide/2, self.high/2-self.xdis)
            self.path.arcTo(0,0, self.wide-2*self.xdis, self.high-2*self.xdis,45,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2-self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis,self.high-2*self.xdis,135,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2, self.high/2+self.xdis)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,225,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2+self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,315,90)
            self.path.closeSubpath()
Пример #29
0
    def __init__(self,parent=None,text='FigLabelWidget'):
        super(FigLabelWidget,self).__init__(parent)
        self.parent=parent
        self.lx=5
        self.text=text
        self.fid=0
        self.stats=None

        self.linecolor=QPalette().light().color()
        self.linecolor.setRgb(157,157,157)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(187,187,187)
        self.brush=QBrush(Qt.SolidPattern)
        self.brush2=QBrush(Qt.SolidPattern)

        self.activeLabel()
 def __init__(self, closeWindowCallback, parent=None):
     QWidget.__init__(self, parent)
     self._parent = parent
     self._closeWindowCallback = closeWindowCallback
     self.setAutoFillBackground(True)
     palette = QPalette()
     palette.setColor(QPalette.Background, Qt.black)
     self.setPalette(palette)
     # Layout
     layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addStretch(1)
     # self.filterOptions = FilterOptionsWidget()
     # # Collapsible layout
     # layout = QHBoxLayout()
     # layout.setContentsMargins(0, 0, 0, 0)
     # layout.setSpacing(0)
     # self.filterOptions.setFixedHeight(0)
     # layout.addWidget(self.filterOptions)
     # # Filter button
     # self.filterIcon = QtGui.QIcon('images/appbar.list.check.svg')
     # self.collapseButton = QPushButton()
     # self.collapseButton.setIcon(self.filterIcon)
     # self.collapseButton.clicked.connect(self.collapseToggle)
     # self.collapseButton.setIconSize(QtCore.QSize(50, 50))
     # self.collapseButton.setStyleSheet("background-color: black")
     # layout.addWidget(self.collapseButton, alignment=Qt.AlignTop)
     # Min/Max button
     self.maxIcon = QtGui.QIcon('images/appbar.max.svg')
     self.restoreIcon = QtGui.QIcon('images/appbar.restore.svg')
     self.minMaxButton = QPushButton()
     self.minMaxButton.setIcon(self.maxIcon)
     self.minMaxButton.clicked.connect(self.minMaxHandler)
     self.minMaxButton.setIconSize(QtCore.QSize(50, 50))
     self.minMaxButton.setStyleSheet("background-color: black")
     layout.addWidget(self.minMaxButton, alignment=Qt.AlignTop|Qt.AlignRight)
     # Exit button
     self.exitIcon = QtGui.QIcon('images/appbar.exit.svg')
     self.exitButton = QPushButton()
     self.exitButton.setIcon(self.exitIcon)
     self.exitButton.clicked.connect(self.exitHandler)
     self.exitButton.setIconSize(QtCore.QSize(50, 50))
     self.exitButton.setStyleSheet("background-color: black")
     layout.addWidget(self.exitButton, alignment=Qt.AlignTop|Qt.AlignRight)
     # Set layout
     self.setLayout(layout)
Пример #31
0
    def inicializa_GUI(self):
        self.dinero = pg.MONEDAS_INICIALES
        self.setWindowTitle('Menú de la Tienda')
        self.move(300, 200)
        self.setWindowIcon(QIcon(pg.PATH_LOGO))
        self.grid_tools = QGridLayout()
        self.grid_recursos = QGridLayout()
        self.label_item = QLabel("ITEM", self)
        self.label_item.setFont(QFont("Times", 16))
        self.label_item_2 = QLabel("ITEM", self)
        self.label_item_2.setFont(QFont("Times", 16))
        self.label_precio = QLabel("PRECIO", self)
        self.label_precio.setFont(QFont("Times", 16))
        self.label_precio_2 = QLabel("PRECIO", self)
        self.label_precio_2.setFont(QFont("Times", 16))
        self.label_accion_0 = QLabel("ACCIONES", self)
        self.label_accion_0.setFont(QFont("Times", 16))
        self.label_accion_1 = QLabel("POSIBLES", self)
        self.label_accion_1.setFont(QFont("Times", 16))
        self.label_accion_2 = QLabel("ACCION", self)
        self.label_accion_2.setFont(QFont("Times", 16))
        self.label_dinero = QLabel("Dinero:", self)
        self.label_dinero.setFont(QFont("Times", 16))
        self.label_dinero.setAlignment(Qt.AlignCenter)
        self.label_dinero_2 = QLabel("$" + str(self.dinero), self)
        self.label_dinero_2.setFont(QFont("Times", 14))
        self.label_dinero_2.setAlignment(Qt.AlignCenter)

        self.boton_salir = QPushButton("Salir", self)
        self.boton_salir.clicked.connect(self.ocultar_tienda)
        self.boton_salir.clicked.connect(self.mostrar_juego)

        self.layout_derecho = QGridLayout()
        self.layout_derecho.setAlignment(Qt.AlignTop)
        self.layout_derecho.addWidget(self.label_dinero, 0, 0)
        self.layout_derecho.addWidget(self.label_dinero_2, 1, 0)
        self.layout_derecho.addWidget(self.boton_salir, 2, 0)

        self.grid_tools.addWidget(self.label_item, 0, 0)
        self.grid_tools.addWidget(self.label_precio, 0, 1)
        self.grid_tools.addWidget(self.label_accion_0, 0, 2)
        self.grid_tools.addWidget(self.label_accion_1, 0, 3)
        self.grid_recursos.addWidget(self.label_item_2, 0, 0)
        self.grid_recursos.addWidget(self.label_precio_2, 0, 1)
        self.grid_recursos.addWidget(self.label_accion_2, 0, 2)

        self.dict_botones_compra = {}
        self.dict_botones_venta = {}

        self.agregar_a_grilla(0, "azada", "$" + str(pp.PRECIO_AZADA), 1)
        self.agregar_a_grilla(0, "hacha", "$" + str(pp.PRECIO_HACHA), 2)
        self.agregar_a_grilla(0, "seed_c", "$" + str(pp.PRECIO_SEMILLA_CHOCLOS), 3)
        self.agregar_a_grilla(0, "seed_a", "$" + str(pp.PRECIO_SEMILLA_ALCACHOFAS), 4)
        self.agregar_a_grilla(1, "alcachofa", "$" + str(pp.PRECIO_ALACACHOFAS), 1)
        self.agregar_a_grilla(1, "choclo", "$" + str(pp.PRECIO_CHOCLOS), 2)
        self.agregar_a_grilla(1, "rama", "$" + str(pp.PRECIO_LEÑA), 3)
        self.agregar_a_grilla(1, "oro", "$" + str(pp.PRECIO_ORO), 4)
        self.agregar_a_grilla(1, "ticket", "$" + str(pp.PRECIO_TICKET), 5)

        self.grid_recursos.setAlignment(Qt.AlignTop)
        self.grid_tools.setAlignment(Qt.AlignTop)
        self.layout_principal = QHBoxLayout()
        self.layout_principal.addSpacing(15)
        self.layout_principal.addLayout(self.grid_tools)
        self.layout_principal.addSpacing(30)
        self.layout_principal.addLayout(self.grid_recursos)
        self.layout_principal.addSpacing(30)
        self.layout_principal.addLayout(self.layout_derecho)
        self.layout_principal.addSpacing(15)
        self.layout_principal_2 = QVBoxLayout()
        self.layout_principal_2.addSpacing(15)
        self.layout_principal_2.addLayout(self.layout_principal)
        self.layout_principal_2.addSpacing(15)
        self.setLayout(self.layout_principal_2)
        fondo = QImage(pg.PATH_FONDO_MAPA)
        fondo_scaled = fondo.scaled(QSize(770, 350))
        palette = QPalette()
        palette.setBrush(10, QBrush(fondo_scaled))
        self.setPalette(palette)
Пример #32
0
    def __init__(self):
        super().__init__()

        self.show_log = False

        # create a palette, used to set color
        self.pe = QPalette()
        """ UI for training  """
        choose_train_data = QPushButton('choose train data')
        self.start_train = QPushButton('Start training')
        self.stop_train = QPushButton('Stop training')

        choose_train_data.clicked.connect(self.show_train_dialog)
        self.start_train.clicked.connect(self.start_train_func)
        self.stop_train.clicked.connect(self.stop_train_func)

        # used to show the chosen training directory
        self.train_dir_edit = QLineEdit()

        # used to show training statics
        self.statics_label = QLabel('')
        self.statics_label.setAlignment(Qt.AlignTop)
        self.statics_label.setAutoFillBackground(True)
        self.pe.setColor(QPalette.Background, Qt.white)
        self.statics_label.setPalette(self.pe)

        self.loss_label = QLabel('')
        self.pe.setColor(QPalette.Background, Qt.white)
        self.loss_label.setAutoFillBackground(True)
        self.loss_label.setPalette(self.pe)
        self.resize_image(path="./buffer/blank.jpg", mode='loss')
        loss_im = QPixmap("./buffer/loss_buffer.jpg")
        loss_im = loss_im.scaledToWidth(430)
        loss_im = loss_im.scaledToHeight(300)
        self.loss_label.setPixmap(loss_im)

        # add buttons, label, and edit to the ui
        grid_train = QGridLayout()
        grid_train.setSpacing(10)

        grid_train.addWidget(choose_train_data, 1, 0)
        grid_train.addWidget(self.train_dir_edit, 1, 1, 1, 3)
        grid_train.addWidget(self.start_train, 1, 4, 1, 2)
        grid_train.addWidget(self.stop_train, 1, 6, 1, 2)
        grid_train.addWidget(self.statics_label, 2, 0, -1, 4)
        grid_train.addWidget(self.loss_label, 2, 4, -1, 4)
        """ UI for testing """
        choose_test_data = QPushButton('choose test data')
        choose_test_data.clicked.connect(self.show_test_dialog)

        self.test_dir_edit = QLineEdit()

        # create a label to show image
        self.image_label = QLabel()
        self.resize_image(path="./buffer/blank.jpg", mode='test')
        test_im = QPixmap("./buffer/test_buffer.jpg")
        test_im = test_im.scaledToWidth(430)
        test_im = test_im.scaledToHeight(430)
        self.image_label.setPixmap(test_im)

        self.results_label = QLabel('Results')
        self.results_label.setAlignment(Qt.AlignCenter)
        self.pe.setColor(QPalette.Background, Qt.lightGray)
        self.results_label.setAutoFillBackground(True)
        self.results_label.setPalette(self.pe)

        # add thses buttons, labels, edit to the ui
        grid_test = QGridLayout()
        grid_test.setSpacing(10)

        grid_test.addWidget(choose_test_data, 1, 0)
        grid_test.addWidget(self.test_dir_edit, 1, 1, 1, 3)
        grid_test.addWidget(self.image_label, 2, 0, -1, 4)
        grid_test.addWidget(self.results_label, 1, 4, 1, 4)

        # create ui for test results
        self.pe.setColor(QPalette.Background, Qt.white)

        collar_label = QLabel('领子设计')
        collar_label.setAlignment(Qt.AlignCenter)
        self.collar_result = QLabel('')
        self.collar_result.setAutoFillBackground(True)
        self.collar_result.setPalette(self.pe)
        self.collar_result.setAlignment(Qt.AlignCenter)

        neckline_label = QLabel('颈线设计')

        neckline_label.setAlignment(Qt.AlignCenter)
        self.neckline_result = QLabel('')
        self.neckline_result.setAutoFillBackground(True)
        self.neckline_result.setPalette(self.pe)
        self.neckline_result.setAlignment(Qt.AlignCenter)

        neck_label = QLabel('脖颈设计')
        neck_label.setAlignment(Qt.AlignCenter)
        self.neck_result = QLabel('')
        self.neck_result.setAutoFillBackground(True)
        self.neck_result.setPalette(self.pe)
        self.neck_result.setAlignment(Qt.AlignCenter)

        lapel_label = QLabel('翻领设计')
        lapel_label.setAlignment(Qt.AlignCenter)
        self.lapel_result = QLabel('')
        self.lapel_result.setAutoFillBackground(True)
        self.lapel_result.setPalette(self.pe)
        self.lapel_result.setAlignment(Qt.AlignCenter)

        coat_label = QLabel('衣长')
        coat_label.setAlignment(Qt.AlignCenter)
        self.coat_result = QLabel('')
        self.coat_result.setAutoFillBackground(True)
        self.coat_result.setPalette(self.pe)
        self.coat_result.setAlignment(Qt.AlignCenter)

        pant_laebl = QLabel('裤长')
        pant_laebl.setAlignment(Qt.AlignCenter)
        self.pant_result = QLabel('')
        self.pant_result.setAutoFillBackground(True)
        self.pant_result.setPalette(self.pe)
        self.pant_result.setAlignment(Qt.AlignCenter)

        skirt_label = QLabel('裙长')
        skirt_label.setAlignment(Qt.AlignCenter)
        self.skirt_result = QLabel('')
        self.skirt_result.setAutoFillBackground(True)
        self.skirt_result.setPalette(self.pe)
        self.skirt_result.setAlignment(Qt.AlignCenter)

        sleeve_label = QLabel('袖长')
        sleeve_label.setAlignment(Qt.AlignCenter)
        self.sleeve_result = QLabel('')
        self.sleeve_result.setAutoFillBackground(True)
        self.sleeve_result.setPalette(self.pe)
        self.sleeve_result.setAlignment(Qt.AlignCenter)

        grid_test.addWidget(collar_label, 2, 4, 1, 2)
        grid_test.addWidget(self.collar_result, 3, 4, 1, 2)
        grid_test.addWidget(neckline_label, 2, 6, 1, 2)
        grid_test.addWidget(self.neckline_result, 3, 6, 1, 2)
        grid_test.addWidget(neck_label, 4, 4, 1, 2)
        grid_test.addWidget(self.neck_result, 5, 4, 1, 2)
        grid_test.addWidget(lapel_label, 4, 6, 1, 2)
        grid_test.addWidget(self.lapel_result, 5, 6, 1, 2)
        grid_test.addWidget(coat_label, 6, 4, 1, 2)
        grid_test.addWidget(self.coat_result, 7, 4, 1, 2)
        grid_test.addWidget(pant_laebl, 6, 6, 1, 2)
        grid_test.addWidget(self.pant_result, 7, 6, 1, 2)
        grid_test.addWidget(skirt_label, 8, 4, 1, 2)
        grid_test.addWidget(self.skirt_result, 9, 4, 1, 2)
        grid_test.addWidget(sleeve_label, 8, 6, 1, 2)
        grid_test.addWidget(self.sleeve_result, 9, 6, 1, 2)
        """ combine two grid """
        upper_grid = QGridLayout()
        upper_grid.setSpacing(10)

        upper_grid.addLayout(grid_train, 1, 0)
        upper_grid.addLayout(grid_test, 2, 0)
        """ show the ui """
        self.setLayout(upper_grid)
        self.setGeometry(300, 100, 890, 860)
        self.setWindowTitle('image classification')
        self.setFixedSize(890, 860)
        self.show()
Пример #33
0
def get_dark_theme():
    dark_palette = QPalette()
    dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.WindowText, Qt.white)
    dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
    dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
    dark_palette.setColor(QPalette.ToolTipText, Qt.white)
    dark_palette.setColor(QPalette.Text, Qt.white)
    dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.ButtonText, Qt.white)
    dark_palette.setColor(QPalette.BrightText, Qt.red)
    dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
    dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    dark_palette.setColor(QPalette.HighlightedText, Qt.black)
    return dark_palette
Пример #34
0
    def __init__(self):
        super().__init__()

        self.runaction = widget.OWAction("Run Hybrid", self)
        self.runaction.triggered.connect(self.run_hybrid)
        self.addAction(self.runaction)

        self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)

        button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal")

        button = gui.button(button_box, self, "Run HYBRID", callback=self.run_hybrid)
        font = QFont(button.font())
        font.setBold(True)
        button.setFont(font)
        palette = QPalette(button.palette()) # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
        button.setPalette(palette) # assign new palette
        button.setFixedHeight(45)

        main_tabs = oasysgui.tabWidget(self.mainArea)
        plot_tab = oasysgui.createTabPage(main_tabs, "Plots")
        out_tab = oasysgui.createTabPage(main_tabs, "Output")

        view_box = oasysgui.widgetBox(plot_tab, "", addSpace=False, orientation="horizontal")
        view_box_1 = oasysgui.widgetBox(view_box, "", addSpace=False, orientation="vertical", width=350)

        self.view_type_combo = gui.comboBox(view_box_1, self, "view_type", label="Plot Results",
                                            labelWidth=220,
                                            items=["No", "Yes"],
                                            callback=self.set_PlotQuality, sendSelectedValue=False, orientation="horizontal")

        self.tabs = oasysgui.tabWidget(plot_tab)

        self.tabs_setting = oasysgui.tabWidget(self.controlArea)
        self.tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
        self.tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5)

        tab_bas = oasysgui.createTabPage(self.tabs_setting, "Basic Setting")
        tab_adv = oasysgui.createTabPage(self.tabs_setting, "Advanced Setting")

        box_1 = oasysgui.widgetBox(tab_bas, "Calculation Parameters", addSpace=True, orientation="vertical", height=120)

        self.cb_ghy_diff_plane = gui.comboBox(box_1, self, "ghy_diff_plane", label="Diffraction Plane", labelWidth=310,
                     items=["Sagittal", "Tangential", "Both (2D)", "Both (1D+1D)"],
                     callback=self.set_DiffPlane,
                     sendSelectedValue=False, orientation="horizontal")

        gui.comboBox(box_1, self, "ghy_calcType", label="Calculation", labelWidth=70,
                     items=self.get_calculation_type_items(),
                     callback=self.set_CalculationType,
                     sendSelectedValue=False, orientation="vertical")

        gui.separator(box_1, 10)


        box_2 = oasysgui.widgetBox(tab_bas, "Numerical Control Parameters", addSpace=True, orientation="vertical", height=140)

        self.le_nbins_x = oasysgui.lineEdit(box_2, self, "ghy_nbins_x", "Number of bins for I(Sagittal) histogram", labelWidth=260, valueType=int, orientation="horizontal")
        self.le_nbins_z = oasysgui.lineEdit(box_2, self, "ghy_nbins_z", "Number of bins for I(Tangential) histogram", labelWidth=260, valueType=int, orientation="horizontal")
        self.le_npeak   = oasysgui.lineEdit(box_2, self, "ghy_npeak", "Number of diffraction peaks", labelWidth=260, valueType=int, orientation="horizontal")
        self.le_fftnpts = oasysgui.lineEdit(box_2, self, "ghy_fftnpts", "Number of points for FFT", labelWidth=260, valueType=int, orientation="horizontal")

        box_3 = oasysgui.widgetBox(tab_adv, "Propagation Parameters", addSpace=True, orientation="vertical", height=240)


        self.cb_distance_to_image_calc = gui.comboBox(box_3, self, "distance_to_image_calc", label="Distance to image", labelWidth=150,
                     items=["Use O.E. Image Plane Distance", "Specify Value"],
                     callback=self.set_DistanceToImageCalc,
                     sendSelectedValue=False, orientation="horizontal")

        self.le_distance_to_image = oasysgui.lineEdit(box_3, self, "ghy_distance", "Distance to Image value", labelWidth=260, valueType=float, orientation="horizontal")

        gui.separator(box_3)

        self.cb_nf = gui.comboBox(box_3, self, "ghy_nf", label="Near Field Calculation", labelWidth=310,
                                             items=["No", "Yes"],
                                             sendSelectedValue=False, orientation="horizontal", callback=self.set_NF)

        self.cb_focal_length_calc = gui.comboBox(box_3, self, "focal_length_calc", label="Focal Length", labelWidth=180,
                     items=["Use O.E. Focal Distance", "Specify Value"],
                     callback=self.set_FocalLengthCalc,
                     sendSelectedValue=False, orientation="horizontal")

        self.le_focal_length = oasysgui.lineEdit(box_3, self, "ghy_focallength", "Focal Length value", labelWidth=200, valueType=float, orientation="horizontal")

        self.le_focal_length_calculated = oasysgui.lineEdit(box_3, self, "ghy_focallength_calculated", "Focal Length calculated", labelWidth=200, valueType=float, orientation="horizontal")
        self.le_focal_length_calculated.setReadOnly(True)
        font = QFont(self.le_focal_length_calculated.font())
        font.setBold(True)
        self.le_focal_length_calculated.setFont(font)
        palette = QPalette(self.le_focal_length_calculated.palette()) # make a copy of the palette
        palette.setColor(QPalette.Text, QColor('dark blue'))
        palette.setColor(QPalette.Base, QColor(243, 240, 160))
        self.le_focal_length_calculated.setPalette(palette)

        box_4 = oasysgui.widgetBox(tab_adv, "Calculation Congruence Parameters", addSpace=True, orientation="vertical", height=200)

        gui.comboBox(box_4, self, "ghy_automatic", label="Analize geometry to avoid unuseful calculations", labelWidth=310,
                     items=["No", "Yes"],
                     sendSelectedValue=False, orientation="horizontal")


        gui.comboBox(box_4, self, "send_original_beam", label="Send Original Beam in case of failure", labelWidth=310,
                                             items=["No", "Yes"],
                                             sendSelectedValue=False, orientation="horizontal")

        self.set_DiffPlane()
        self.set_DistanceToImageCalc()
        self.set_CalculationType()
        self.set_NF()

        self.initializeTabs()

        adv_other_box = oasysgui.widgetBox(tab_bas, "Optional file output", addSpace=False, orientation="vertical")

        gui.comboBox(adv_other_box, self, "file_to_write_out", label="Files to write out", labelWidth=220,
                     items=["None", "Debug (star.xx)"],
                     sendSelectedValue=False,
                     orientation="horizontal")

        self.shadow_output = oasysgui.textArea(height=580, width=800)

        out_box = gui.widgetBox(out_tab, "System Output", addSpace=True, orientation="horizontal")
        out_box.layout().addWidget(self.shadow_output)

        self.set_PlotQuality()
Пример #35
0
def launch():
    # from utils.install_punkt import install_punkt

    # install_punkt()

    app = QApplication(sys.argv)

    try:
        file = sys.argv[1]
    except IndexError:  # File not given
        file = get_last_file()
    app.setStyle('Fusion')
    palette = QPalette()
    editor = configs[choiceIndex]['editor']

    ex = Main(app, palette, editor)
    palette.setColor(QPalette.Window, QColor(editor["windowColor"]))
    palette.setColor(QPalette.WindowText, QColor(editor["windowText"]))
    palette.setColor(QPalette.Base, QColor(editor["editorColor"]))
    palette.setColor(QPalette.AlternateBase, QColor(editor["alternateBase"]))
    palette.setColor(QPalette.ToolTipBase, QColor(editor["ToolTipBase"]))
    palette.setColor(QPalette.ToolTipText, QColor(editor["ToolTipText"]))
    palette.setColor(QPalette.Text, QColor(editor["editorText"]))
    palette.setColor(QPalette.Button, QColor(editor["buttonColor"]))
    palette.setColor(QPalette.ButtonText, QColor(editor["buttonTextColor"]))
    palette.setColor(QPalette.Highlight,
                     QColor(editor["HighlightColor"]).lighter())
    palette.setColor(QPalette.HighlightedText,
                     QColor(editor["HighlightedTextColor"]))
    app.setPalette(palette)
    app.setStyleSheet(
        material_blue)  # uncomment this to have a material blue theme
    ex.show()
    if file is not None:
        ex.openFile(file)
        ex.openProjectWithPath(os.getcwd())

    sys.exit(app.exec_())
Пример #36
0
    def build_gui(self):
        self.tabs_setting = oasysgui.tabWidget(self.controlArea)
        self.tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
        self.tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5)

        self.tab_bas = oasysgui.createTabPage(self.tabs_setting,
                                              "O.E. Setting")
        self.tab_pro = oasysgui.createTabPage(self.tabs_setting,
                                              "Calculation Setting")

        main_box = oasysgui.widgetBox(self.tab_bas,
                                      "O.E. Input Parameters",
                                      orientation="vertical",
                                      width=self.CONTROL_AREA_WIDTH - 20)

        oasysgui.lineEdit(main_box,
                          self,
                          "oe_name",
                          "O.E. Name",
                          labelWidth=120,
                          valueType=str,
                          orientation="horizontal")

        oasysgui.lineEdit(main_box,
                          self,
                          "alpha",
                          "Incidence Angle [deg]",
                          labelWidth=240,
                          valueType=float,
                          orientation="horizontal")
        self.le_length = oasysgui.lineEdit(main_box,
                                           self,
                                           "length",
                                           "Length",
                                           labelWidth=240,
                                           valueType=float,
                                           orientation="horizontal")

        self.build_mirror_specific_gui(main_box)

        gui.comboBox(main_box,
                     self,
                     "ignore",
                     label="Ignore",
                     items=["No", "Yes"],
                     labelWidth=240,
                     sendSelectedValue=False,
                     orientation="horizontal")

        gui.separator(main_box)

        self.tabs_mirror = oasysgui.tabWidget(main_box)
        self.tabs_mirror.setFixedWidth(self.CONTROL_AREA_WIDTH - 40)

        self.tab_pos = oasysgui.createTabPage(self.tabs_mirror, "Position")
        if self.has_figure_error_box:
            self.tab_err = oasysgui.createTabPage(self.tabs_mirror,
                                                  "Figure Error")
        self.tab_dis = oasysgui.createTabPage(self.tabs_mirror, "Displacement")

        super(OWOpticalElement, self).build_positioning_directive_box(
            container_box=self.tab_pos,
            width=self.CONTROL_AREA_WIDTH - 50,
            element_type=ElementType.MIRROR)

        displacement_box = oasysgui.widgetBox(self.tab_dis,
                                              "Small Displacements",
                                              orientation="vertical",
                                              width=self.CONTROL_AREA_WIDTH -
                                              50)

        gui.comboBox(displacement_box,
                     self,
                     "use_small_displacements",
                     label="Small Displacements",
                     items=["No", "Yes"],
                     labelWidth=240,
                     callback=self.set_UseSmallDisplacement,
                     sendSelectedValue=False,
                     orientation="horizontal")

        self.use_small_displacements_box = oasysgui.widgetBox(
            displacement_box,
            "",
            addSpace=True,
            orientation="vertical",
            height=150,
            width=self.CONTROL_AREA_WIDTH - 65)
        self.use_small_displacements_box_empty = oasysgui.widgetBox(
            displacement_box,
            "",
            addSpace=True,
            orientation="vertical",
            height=150,
            width=self.CONTROL_AREA_WIDTH - 65)

        oasysgui.lineEdit(self.use_small_displacements_box,
                          self,
                          "rotation",
                          "Rotation [deg]",
                          labelWidth=240,
                          valueType=float,
                          orientation="horizontal")
        self.le_transverse = oasysgui.lineEdit(
            self.use_small_displacements_box,
            self,
            "transverse",
            "Transverse displacement",
            labelWidth=240,
            valueType=float,
            orientation="horizontal")
        self.le_longitudinal = oasysgui.lineEdit(
            self.use_small_displacements_box,
            self,
            "longitudinal",
            "Longitudinal displacement",
            labelWidth=240,
            valueType=float,
            orientation="horizontal")

        self.set_UseSmallDisplacement()

        # ---------------------------------------------------------------------------
        if self.has_figure_error_box:
            figure_error_tab = oasysgui.tabWidget(self.tab_err)
            error_tab = oasysgui.createTabPage(figure_error_tab,
                                               "Error Profile")
            roughness_tab = oasysgui.createTabPage(figure_error_tab,
                                                   "Roughness")

            figure_error_box = oasysgui.widgetBox(
                error_tab,
                "",
                orientation="vertical",
                width=self.CONTROL_AREA_WIDTH - 65)
            roughness_box = oasysgui.widgetBox(roughness_tab,
                                               "",
                                               orientation="vertical",
                                               width=self.CONTROL_AREA_WIDTH -
                                               65)

            gui.comboBox(figure_error_box,
                         self,
                         "use_figure_error",
                         label="Error Profile",
                         items=["None", "User Defined"],
                         labelWidth=240,
                         callback=self.set_UseFigureError,
                         sendSelectedValue=False,
                         orientation="horizontal")

            self.use_figure_error_box = oasysgui.widgetBox(
                figure_error_box,
                "",
                addSpace=True,
                orientation="vertical",
                height=150)
            self.use_figure_error_box_empty = oasysgui.widgetBox(
                figure_error_box,
                "",
                addSpace=True,
                orientation="vertical",
                height=150)

            file_box = oasysgui.widgetBox(self.use_figure_error_box,
                                          "",
                                          addSpace=False,
                                          orientation="horizontal")
            self.le_figure_error_file = oasysgui.lineEdit(
                file_box,
                self,
                "figure_error_file",
                "File Name",
                labelWidth=100,
                valueType=str,
                orientation="horizontal")
            gui.button(file_box,
                       self,
                       "...",
                       callback=self.selectFigureErrorFile)

            self.le_figure_error_step = oasysgui.lineEdit(
                self.use_figure_error_box,
                self,
                "figure_error_step",
                "Step",
                labelWidth=240,
                valueType=float,
                orientation="horizontal")
            oasysgui.lineEdit(self.use_figure_error_box,
                              self,
                              "figure_error_amplitude_scaling",
                              "Amplitude scaling factor",
                              labelWidth=240,
                              valueType=float,
                              orientation="horizontal")
            oasysgui.lineEdit(self.use_figure_error_box,
                              self,
                              "figure_error_um_conversion",
                              "User file u.m. to [m] factor",
                              labelWidth=240,
                              valueType=float,
                              orientation="horizontal")

            self.set_UseFigureError()

            gui.comboBox(roughness_box,
                         self,
                         "use_roughness",
                         label="Roughness",
                         items=["None", "User Defined"],
                         labelWidth=240,
                         callback=self.set_UseRoughness,
                         sendSelectedValue=False,
                         orientation="horizontal")

            self.use_roughness_box = oasysgui.widgetBox(roughness_box,
                                                        "",
                                                        addSpace=True,
                                                        orientation="vertical",
                                                        height=150)
            self.use_roughness_box_empty = oasysgui.widgetBox(
                roughness_box,
                "",
                addSpace=True,
                orientation="vertical",
                height=150)

            file_box = oasysgui.widgetBox(self.use_roughness_box,
                                          "",
                                          addSpace=False,
                                          orientation="horizontal")
            self.le_roughness_file = oasysgui.lineEdit(
                file_box,
                self,
                "roughness_file",
                "File Name",
                labelWidth=100,
                valueType=str,
                orientation="horizontal")
            gui.button(file_box,
                       self,
                       "...",
                       callback=self.selectRoughnessFile)

            oasysgui.lineEdit(self.use_roughness_box,
                              self,
                              "roughness_x_scaling",
                              "x user file u.m. to [m]   factor",
                              labelWidth=240,
                              valueType=float,
                              orientation="horizontal")
            oasysgui.lineEdit(self.use_roughness_box,
                              self,
                              "roughness_y_scaling",
                              "y user file u.m. to [m^3] factor",
                              labelWidth=240,
                              valueType=float,
                              orientation="horizontal")

            gui.comboBox(self.use_roughness_box,
                         self,
                         "roughness_fit_data",
                         label="Fit numeric data with power law",
                         items=["No", "Yes"],
                         labelWidth=240,
                         sendSelectedValue=False,
                         orientation="horizontal")

            self.set_UseRoughness()

        # ---------------------------------------------------------------------------

        calculation_box = oasysgui.widgetBox(self.tab_pro,
                                             "Calculation Parameters",
                                             orientation="vertical",
                                             width=self.CONTROL_AREA_WIDTH -
                                             20)

        gui.comboBox(calculation_box,
                     self,
                     "calculation_type",
                     label="Numeric Integration",
                     items=[
                         "Automatic Number of Points",
                         "User Defined Number of Points"
                     ],
                     labelWidth=140,
                     callback=self.set_CalculationType,
                     sendSelectedValue=False,
                     orientation="horizontal")

        self.empty_box = oasysgui.widgetBox(calculation_box,
                                            "",
                                            orientation="vertical",
                                            width=self.CONTROL_AREA_WIDTH - 40,
                                            height=50)
        self.number_box = oasysgui.widgetBox(calculation_box,
                                             "",
                                             orientation="vertical",
                                             width=self.CONTROL_AREA_WIDTH -
                                             40,
                                             height=50)

        oasysgui.lineEdit(self.number_box,
                          self,
                          "number_of_points",
                          "Number of Points",
                          labelWidth=240,
                          valueType=int,
                          orientation="horizontal")

        self.set_CalculationType()

        parallel_box = oasysgui.widgetBox(self.tab_pro,
                                          "Parallel Computing",
                                          orientation="vertical",
                                          width=self.CONTROL_AREA_WIDTH - 20)

        gui.comboBox(parallel_box,
                     self,
                     "use_multipool",
                     label="Use Parallel Processing",
                     items=["No", "Yes"],
                     labelWidth=240,
                     callback=self.set_Multipool,
                     sendSelectedValue=False,
                     orientation="horizontal")

        self.use_multipool_box = oasysgui.widgetBox(
            parallel_box,
            "",
            addSpace=False,
            orientation="vertical",
            height=100,
            width=self.CONTROL_AREA_WIDTH - 40)
        self.use_multipool_box_empty = oasysgui.widgetBox(
            parallel_box,
            "",
            addSpace=False,
            orientation="vertical",
            height=100,
            width=self.CONTROL_AREA_WIDTH - 40)

        oasysgui.lineEdit(self.use_multipool_box,
                          self,
                          "n_pools",
                          "Nr. Parallel Processes",
                          labelWidth=240,
                          valueType=int,
                          orientation="horizontal")

        gui.separator(self.use_multipool_box)

        gui.comboBox(self.use_multipool_box,
                     self,
                     "force_cpus",
                     label="Ignore Nr. Processes > Nr. CPUs",
                     items=["No", "Yes"],
                     labelWidth=240,
                     sendSelectedValue=False,
                     orientation="horizontal")

        le = oasysgui.lineEdit(self.use_multipool_box,
                               self,
                               "number_of_cpus",
                               "Nr. Available CPUs",
                               labelWidth=240,
                               valueType=float,
                               orientation="horizontal")
        le.setReadOnly(True)
        font = QFont(le.font())
        font.setBold(True)
        le.setFont(font)
        palette = QPalette(le.palette())
        palette.setColor(QPalette.Text, QColor('dark blue'))
        palette.setColor(QPalette.Base, QColor(243, 240, 140))
        le.setPalette(palette)

        self.set_Multipool()
Пример #37
0
class AmountEdit(FreezableLineEdit):
    shortcut = pyqtSignal()

    def __init__(self, base_unit, is_int=False, parent=None):
        QLineEdit.__init__(self, parent)
        # This seems sufficient for hundred-BTC amounts with 8 decimals
        self.setFixedWidth(16 * char_width_in_lineedit())
        self.base_unit = base_unit
        self.textChanged.connect(self.numbify)
        self.is_int = is_int
        self.is_shortcut = False
        self.help_palette = QPalette()
        self.extra_precision = 0

    def decimal_point(self):
        return 8

    def max_precision(self):
        return self.decimal_point() + self.extra_precision

    def numbify(self):
        text = self.text().strip()
        if text == '!':
            self.shortcut.emit()
            return
        pos = self.cursorPosition()
        chars = '0123456789'
        if not self.is_int: chars += '.'
        s = ''.join([i for i in text if i in chars])
        if not self.is_int:
            if '.' in s:
                p = s.find('.')
                s = s.replace('.', '')
                s = s[:p] + '.' + s[p:p + self.max_precision()]
        self.setText(s)
        # setText sets Modified to False.  Instead we want to remember
        # if updates were because of user modification.
        self.setModified(self.hasFocus())
        self.setCursorPosition(pos)

    def paintEvent(self, event):
        QLineEdit.paintEvent(self, event)
        if self.base_unit:
            panel = QStyleOptionFrame()
            self.initStyleOption(panel)
            textRect = self.style().subElementRect(QStyle.SE_LineEditContents,
                                                   panel, self)
            textRect.adjust(2, 0, -10, 0)
            painter = QPainter(self)
            painter.setPen(
                self.help_palette.brush(QPalette.Disabled,
                                        QPalette.Text).color())
            painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter,
                             self.base_unit())

    def get_amount(self) -> Union[None, Decimal, int]:
        try:
            return (int if self.is_int else Decimal)(str(self.text()))
        except:
            return None

    def setAmount(self, x):
        self.setText("%d" % x)
Пример #38
0
    def __init__(self, MainWindow):
        self.mainWindow = MainWindow
        self.mainWindow.setWindowIcon(QIcon("media/cat.ico"))
        self.mainWindow.setFixedSize(self.mainWindow.minimumSize())

        config = configparser.ConfigParser()
        # gameMode = 0,1,2,3,4,5,6,7代表:
        # 标准、win7、竞速无猜、强无猜、弱无猜、准无猜、强可猜、弱可猜
        if config.read('gameSetting.ini'):
            self.timesLimit = config.getint('DEFAULT', 'timesLimit')
            self.enuLimit = config.getint('DEFAULT', 'enuLimit')
            self.gameMode = config.getint('DEFAULT', 'gameMode')
            self.mainWindow.setWindowOpacity(
                (config.getint('DEFAULT', 'transparency') + 1) / 100)
            self.pixSize = config.getint('DEFAULT', 'pixSize')
            self.mainWindow.move(config.getint('DEFAULT', 'mainWinTop'),
                                 config.getint('DEFAULT', 'mainWinLeft'))
            self.row = config.getint("DEFAULT", "row")
            self.column = config.getint("DEFAULT", "column")
            self.mineNum = config.getint("DEFAULT", "mineNum")
            self.auto_replay = config.getint("DEFAULT",
                                             "auto_replay")  # 完成度低于该百分比炸雷自动重开
            self.auto_show_score = config.getint("DEFAULT",
                                                 "auto_show_score")  # 自动弹成绩
            self.gameover_flag = config.getint("DEFAULT",
                                               "gameover_flag")  # 游戏结束后自动标雷
            if (self.row, self.column, self.mineNum) == (8, 8, 10):
                self.min3BV = config.getint('BEGINNER', 'min3BV')
                self.max3BV = config.getint('BEGINNER', 'max3BV')
            elif (self.row, self.column, self.mineNum) == (16, 16, 40):
                self.min3BV = config.getint('INTERMEDIATE', 'min3BV')
                self.max3BV = config.getint('INTERMEDIATE', 'max3BV')
            elif (self.row, self.column, self.mineNum) == (16, 30, 99):
                self.min3BV = config.getint('EXPERT', 'min3BV')
                self.max3BV = config.getint('EXPERT', 'max3BV')
            else:
                self.min3BV = config.getint('CUSTOM', 'min3BV')
                self.max3BV = config.getint('CUSTOM', 'max3BV')
            self.readPredefinedBoard()
        else:
            # 找不到配置文件就初始化
            self.min3BV = 100
            self.max3BV = 381
            self.timesLimit = 1000
            self.enuLimit = 30
            self.gameMode = 0
            self.mainWindow.setWindowOpacity(1)
            self.pixSize = 20
            self.mainWindow.move(100, 200)
            self.row = 16
            self.column = 30
            self.mineNum = 99
            self.auto_replay = -1
            self.auto_show_score = 101
            self.gameover_flag = 1
            config["DEFAULT"] = {
                'timesLimit': 1000,
                'enuLimit': 30,
                'gameMode': 0,
                'transparency': 100,
                'pixSize': 20,
                'mainWinTop': 100,
                'mainWinLeft': 200,
                'row': 16,
                'column': 30,
                'mineNum': 99,
                "auto_replay": -1,
                "auto_show_score": 101,
                "gameover_flag": 1,
            }
            config["BEGINNER"] = {
                'min3BV': 2,
                'max3BV': 54,
            }
            config["INTERMEDIATE"] = {
                'min3BV': 30,
                'max3BV': 216,
            }
            config["EXPERT"] = {
                'min3BV': 100,
                'max3BV': 381,
            }
            config["CUSTOM"] = {
                'min3BV': 1,
                'max3BV': 9999,
            }
            config["CUSTOM_PRESET_4"] = {
                'row': 16,
                'column': 16,
                'mineNum': 72,
                'gameMode': 2,
                'pixSize': 20,
                'timesLimit': 100000,
                'enuLimit': 30,
                'min3BV': 0,
                'max3BV': 9999,
            }
            config["CUSTOM_PRESET_5"] = {
                'row': 16,
                'column': 30,
                'mineNum': 120,
                'gameMode': 2,
                'pixSize': 20,
                'timesLimit': 100000,
                'enuLimit': 30,
                'min3BV': 0,
                'max3BV': 9999,
            }
            config["CUSTOM_PRESET_6"] = {
                'row': 24,
                'column': 36,
                'mineNum': 200,
                'gameMode': 2,
                'pixSize': 20,
                'timesLimit': 100000,
                'enuLimit': 30,
                'min3BV': 0,
                'max3BV': 9999,
            }
            with open('gameSetting.ini', 'w') as configfile:
                config.write(configfile)  # 将对象写入文件

        self.setupUi(self.mainWindow)
        self.importLEDPic(self.pixSize)  # 导入图片

        # self.mineLabel = []  # 局面
        self.initMineArea()
        self.label_2.leftRelease.connect(self.gameRestart)
        self.label_2.setPixmap(self.pixmapNum[14])
        self.label_2.setScaledContents(True)
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.black)  # 设置字体颜色
        self.label_31.setPalette(pe)
        self.label_31.setFont(QFont("Arial", 20, QFont.Bold))
        self.label_32.setPalette(pe)
        self.label_32.setFont(QFont("Arial", 20, QFont.Bold))
        self.label_33.setPalette(pe)
        self.label_33.setFont(QFont("Arial", 20, QFont.Bold))
        self.label_11.setPalette(pe)
        self.label_11.setFont(QFont("Arial", 12, QFont.Bold))
        self.label_12.setPalette(pe)
        self.label_12.setFont(QFont("Arial", 12, QFont.Bold))
        self.label_13.setPalette(pe)
        self.label_13.setFont(QFont("Arial", 12, QFont.Bold))
        self.label_info.setPalette(pe)  # 最下面的框
        self.label_info.setFont(QFont("Arial", 20, QFont.Bold))
        self.label_info.setText(str(self.mineNum))
Пример #39
0
 def __draw_back(self):
     """初始化背景为黑色"""
     self.setAutoFillBackground(True)
     palette = QPalette()
     palette.setColor(QPalette.Window, QColor('#000000'))
     self.setPalette(palette)
Пример #40
0
class Main_Foram_Dialog(QtWidgets.QWidget):
    """
	Class documentation goes here.
	"""
    def __init__(self, parent=None):
        """
		Constructor
		@param parent reference to the parent widget
		@type QWidget
		"""
        super(Main_Foram_Dialog, self).__init__(parent)
        self.UI = Ui_Main_Foram_Dialog()
        self.UI.setupUi(self)
        #设置背景
        self.main_p = QPalette()
        self.main_p.setColor(QPalette.Background, QColor('#87CEFA'))
        self.setAutoFillBackground(True)
        self.setPalette(self.main_p)
        self.material_content = []

        #初始化mat_type_listWidget
        self.update_database()
        # if items in mat_type_listWidget are selected, get_item is activated
        self.UI.add_pushButton.clicked.connect(
            lambda: self.add_item_to_database())
        self.UI.mat_type_listWidget.itemClicked.connect(
            lambda: self.get_item())
        self.UI.pushButton_ok.clicked.connect(lambda: self.write_result())
        self.UI.fresh_Button.clicked.connect(lambda: self.fresh())
        self.UI.mat_type_listWidget.itemClicked.connect(
            lambda: self.set_content_tableWidget())
        self.UI.del_pushButton.clicked.connect(lambda: self.del_database())

    #弹出添加数据库窗口
    def add_item_to_database(self):
        self.db_input = Ui_Database_Dialog()
        self.main_db_input = QtWidgets.QWidget()
        self.db_input.setupUi(self.main_db_input)
        self.main_db_input.show()
        self.main_db_input.resize(470, 540)
        self.main_db_input.setFixedSize(470, 540)
        #设置背景
        self.main_p = QPalette()
        self.main_p.setColor(QPalette.Background, QColor('#C1CDCD'))
        self.main_db_input.setAutoFillBackground(True)
        self.main_db_input.setPalette(self.main_p)
        #在content_tableWidget中设置表头
        horizontalHeader = ['ZAID', 'Nuclide_Name', 'Ion_Density']
        self.db_input.db_tableWidget.setColumnCount(
            len(horizontalHeader))  #设置列数
        self.db_input.db_tableWidget.setHorizontalHeaderLabels(
            horizontalHeader)  #添加表头

        #self.db_input.db_ok_pushButton.setEnabled(False)
        self.db_input.import_excel_pushButton.clicked.connect(
            lambda: self.set_db_tab_widget_from_excel())
        self.db_input.db_cacel_pushButton.clicked.connect(
            self.main_db_input.close)
        self.db_input.db_ok_pushButton.clicked.connect(
            lambda: self.add_database())
        self.db_input.add_pushButton.clicked.connect(lambda: self.addrow())
        self.db_input.del_pushButton.clicked.connect(lambda: self.delrow())

    #在数据库窗口中添加行
    def addrow(self):
        current_row = self.db_input.db_tableWidget.currentRow()
        if current_row == -1:
            current_row = self.db_input.db_tableWidget.rowCount()
        self.db_input.db_tableWidget.insertRow(current_row)

    #在数据库窗口中删除行
    def delrow(self):
        current_row = self.db_input.db_tableWidget.currentRow()
        if current_row != -1:
            self.db_input.db_tableWidget.removeRow(current_row)

    #db_tableWidget数据是否合法
    def judge_format_correct(self):
        flag = True
        for i in range(self.db_input.db_tableWidget.rowCount()):
            try:
                ZAID = self.db_input.db_tableWidget.item(i, 0).text()
                Nuclide_Name = self.db_input.db_tableWidget.item(i, 1).text()
                Ion_Density = self.db_input.db_tableWidget.item(i, 2).text()
                float_Ion_Density = float(Ion_Density)
            except:
                flag = False
            else:
                if not ZAID or not Nuclide_Name or not float_Ion_Density:
                    flag = False
        return flag

    #删除数据库
    def del_database(self):
        table_name = self.UI.mat_type_listWidget.currentItem().text()
        reply = QMessageBox.question(self, '提示', '确定要删除材料: %s ' % table_name,
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            conn = sqlite3.connect('data.db')
            cur = conn.cursor()
            sql = 'DROP TABLE %s' % table_name
            cur.execute(sql)
            cur.close()
            conn.commit()
            conn.close()
            #更新mat_type_listWidget列表
            self.update_database()
            self.UI.content_tableWidget.setColumnCount(
                0)  #清空content_tableWidget
            self.UI.content_tableWidget.setRowCount(0)
        else:
            pass

    #更新数据库
    def update_database(self):
        #初始化mat_type_listWidget
        self.UI.mat_type_listWidget.clear()
        conn = sqlite3.connect('data.db')
        cur = conn.cursor()
        sql = "SELECT name FROM sqlite_master WHERE type='table' order by name"
        cur.execute(sql)
        item = cur.fetchall()
        for lst in item:
            self.UI.mat_type_listWidget.addItem(lst[0])
        cur.close()
        conn.commit()
        conn.close()

    #警告对话框
    def warning_dlg(self, text):
        msgBox = QMessageBox()
        msgBox.setWindowTitle('警告')
        msgBox.setIcon(QMessageBox.Warning)
        msgBox.setText("%s" % text)
        msgBox.setStandardButtons(QMessageBox.Ok)
        reply = msgBox.exec()

    #数据库窗口,从Excel中读取数据,并写去到db_tableWidget
    def set_db_tab_widget_from_excel(self):
        db_text = self.db_input.db_name_lineEdit.text()
        try:
            database_name = db_text
            insert_data = self.read_txt(db_text)
            #在content_tableWidget中写数据
            horizontalHeader = ['ZAID', 'Nuclide_Name', 'Ion_Density']
            self.db_input.db_tableWidget.setColumnCount(
                len(horizontalHeader))  #设置列数
            self.db_input.db_tableWidget.setRowCount(len(
                insert_data[0]))  #设置行数
            self.db_input.db_tableWidget.setHorizontalHeaderLabels(
                horizontalHeader)  #添加表头
            for i in range(self.db_input.db_tableWidget.rowCount()):
                for j in range(self.db_input.db_tableWidget.columnCount()):
                    self.db_input.db_tableWidget.setItem(
                        i, j, QTableWidgetItem(insert_data[j][i]))  #写入数据
            flag = self.judge_format_correct()
            if flag and db_text:
                self.db_input.db_name_lineEdit.setEnabled(False)

            #设置tableWidget格式
            for index in range(self.db_input.db_tableWidget.columnCount()):
                headItem = self.db_input.db_tableWidget.horizontalHeaderItem(
                    index)
                headItem.setFont(QFont("song", 12, QFont.Bold))
                headItem.setForeground(QColor(60, 60, 60))
                headItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                self.db_input.db_tableWidget.resizeColumnsToContents()
                self.db_input.db_tableWidget.resizeRowsToContents()
                self.db_input.db_tableWidget.horizontalHeader(
                ).setSectionResizeMode(QHeaderView.Stretch)  #自适应窗口
        except:
            self.warning_dlg("材料名称为空,请输入材料名称")

    # 读取db_tableWidget数据,并写入到database中
    def add_database(self):
        flag = self.judge_format_correct()
        db_text = self.db_input.db_name_lineEdit.text()
        if db_text:
            if flag:
                table_name = db_text
                ZAID = []
                Nuclide_Name = []
                Ion_Density = []
                for i in range(self.db_input.db_tableWidget.rowCount()):
                    ZAID.append(self.db_input.db_tableWidget.item(i, 0).text())
                    Nuclide_Name.append(
                        self.db_input.db_tableWidget.item(i, 1).text())
                    Ion_Density.append(
                        self.db_input.db_tableWidget.item(i, 2).text())
                #连接数据库,创建游标
                conn = sqlite3.connect('data.db')
                cur = conn.cursor()
                sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{0}'".format(
                    table_name)
                cur.execute(sql)
                judge_if_exits_tab = cur.fetchall()[0][0]  #如果存在返回1,否则返回0
                if judge_if_exits_tab:
                    #sql='replace into %s(ZAID TEXT,NAME TEXT,Ion_Density REAL) values(?,?,?)'%table_name
                    #cur.executemany(sql, self.generate_tuple_data(ZAID,Nuclide_Name,Ion_Density))
                    #如果表存在,先删除
                    sql = 'DROP TABLE %s' % table_name
                    cur.execute(sql)
                    sql = 'CREATE TABLE %s(ZAID TEXT,NAME TEXT,Ion_Density REAL)' % table_name
                    cur.execute(sql)
                    #批量导入,减少提交事务的次数,可以提高速度
                    sql = 'INSERT INTO %s VALUES(?,?,?)' % table_name
                    cur.executemany(
                        sql,
                        self.generate_tuple_data(ZAID, Nuclide_Name,
                                                 Ion_Density))
                    cur.close()
                    conn.commit()
                    conn.close()
                else:
                    sql = 'CREATE TABLE IF NOT EXISTS %s(ZAID TEXT,NAME TEXT,Ion_Density REAL)' % table_name
                    cur.execute(sql)
                    #批量导入,减少提交事务的次数,可以提高速度
                    sql = 'INSERT INTO %s VALUES(?,?,?)' % table_name
                    cur.executemany(
                        sql,
                        self.generate_tuple_data(ZAID, Nuclide_Name,
                                                 Ion_Density))
                    cur.close()
                    conn.commit()
                    conn.close()
                self.UI.mat_type_listWidget.addItem(table_name)
                self.main_db_input.close()  #关闭窗口
            else:
                self.warning_dlg("核子密度格式有误,请重新输入")
        else:
            self.warning_dlg("材料名称为空,请重新输入")

    #读取文本文件
    def read_txt(self, table_name):
        ZAID = []
        Nuclide_Name = []
        Ion_Density = []
        file_dir = os.getcwd()
        filename, _ = QFileDialog.getOpenFileName(self, 'Open file', './')
        with open(filename, 'r') as f:
            pattern = re.compile(
                r'(\w+)\s+(\w+)\s+(\d{1,}(\.\d{1,})?([E,e][-]?\d*)?)')
            for line in f:
                line = line.strip()
                serch_mark = pattern.search(line)
                try:
                    ZAID.append(serch_mark.group(1))
                    Nuclide_Name.append(serch_mark.group(2))
                    Ion_Density_str = "{:<.8e}".format(
                        float(serch_mark.group(3)))
                    Ion_Density.append(Ion_Density_str)
                except:
                    continue
            insert_data = [ZAID, Nuclide_Name, Ion_Density]
            f.close()
            return insert_data

        #读取Excel文件
        #wb = openpyxl.load_workbook(filename,data_only=True)  #data_only=True可以将公式转化为数值
        #ws = wb.get_sheet_by_name(table_name)
        #contents=[]
        #for column in list(ws.columns):
        #contents.append(column)
        #ZAID_item=contents[0][1:]            #第1列
        #Nuclide_Name_item=contents[1][1:]    #第2列
        #Ion_Density_item=contents[2][1:]     #第3列
        #ZAID=[]
        #Nuclide_Name=[]
        #Ion_Density=[]
        #for i in range(len(ZAID_item)):
        #ZAID.append(str(ZAID_item[i].value))
        #Nuclide_Name.append(str(Nuclide_Name_item[i].value))
        #Ion_Density_str='{:.5e}'.format(Ion_Density_item[i].value)
        #Ion_Density.append(Ion_Density_str)
        #insert_data=[ZAID,Nuclide_Name,Ion_Density]
        #return insert_data

    def generate_tuple_data(self, ZAID, Nuclide_Name, Ion_Density):
        for i in range(len(ZAID)):
            row = ZAID[i], Nuclide_Name[i], Ion_Density[i]
            yield tuple(row)

    # pop sub dialog, and complete Interaction with main window
    def get_item(self):
        #str1=self.UI.mat_type_listWidget.currentItem().text()
        self.input_dialg = Ui_vol_fra_input_Dialog()
        self.dilag_main = QtWidgets.QWidget()
        self.input_dialg.setupUi(self.dilag_main)
        self.dilag_main.show()
        self.dilag_main.setFixedSize(400, 180)
        self.input_dialg.ok_volume_pushButton.clicked.connect(
            lambda: self.get_LineEdit_content(self.input_dialg.
                                              volume_input_lineEdit.text()))
        self.input_dialg.cacel_volume_pushButton_2.clicked.connect(
            self.dilag_main.close)

    #get contents in input_dialg, and check if it is effective
    def get_LineEdit_content(self, item):
        is_digit_mark = re.match(r'\d{1,}(\.\d{1,})?', item)
        try:
            match_item = is_digit_mark.group(0)
            if len(match_item) == len(item):
                self.material_content.append(
                    float(item))  #get contents ininput_dialg
                #print('material is {:<6.4f}'.format(float(item)))
                #self.ok_volume_pushButton.clicked.connect(lambda: self.set_material_content(material_content))
                self.dilag_main.close()  #hide sub window
                self.UI.selected_listWidget.addItem(
                    self.UI.mat_type_listWidget.currentItem().text(
                    ))  #set selected_listWidget item

            else:
                msgBox = QMessageBox()
                msgBox.setWindowTitle('警告')
                msgBox.setIcon(QMessageBox.Warning)
                msgBox.setText("输入数据类型错误,请重新输入一个数")
                msgBox.setStandardButtons(QMessageBox.Ok)
                reply = msgBox.exec()
                self.input_dialg.volume_input_lineEdit.setText(
                    '')  #if fail, set null
        except:
            self.warning_dlg("输入数据类型错误,请重新输入一个数")

    #从数据库读取数据并写到tableWidget中
    def set_content_tableWidget(self):
        table_name = self.UI.mat_type_listWidget.currentItem().text()
        ZAID, Nuclide_Name, Ion_Density = self.read_database(
            table_name)  #从数据库读取每个表
        insert_data = [ZAID, Nuclide_Name, Ion_Density]
        #在content_tableWidget中写数据
        horizontalHeader = ['ZAID', 'Nuclide_Name', 'Ion_Density']
        self.UI.content_tableWidget.setColumnCount(
            len(horizontalHeader))  #设置列数
        self.UI.content_tableWidget.setRowCount(len(ZAID))  #设置行数
        self.UI.content_tableWidget.setHorizontalHeaderLabels(
            horizontalHeader)  #添加表头
        for i in range(self.UI.content_tableWidget.rowCount()):
            for j in range(self.UI.content_tableWidget.columnCount()):
                self.UI.content_tableWidget.setItem(
                    i, j, QTableWidgetItem(insert_data[j][i]))  #写入数据
        #设置tableWidget格式
        for index in range(self.UI.content_tableWidget.columnCount()):
            headItem = self.UI.content_tableWidget.horizontalHeaderItem(index)
            headItem.setFont(QFont("song", 12, QFont.Bold))
            headItem.setForeground(QColor(60, 60, 60))
            headItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
            self.UI.content_tableWidget.setEditTriggers(
                QTableWidget.NoEditTriggers)  #内容无法编辑
            self.UI.content_tableWidget.resizeColumnsToContents()
            self.UI.content_tableWidget.resizeRowsToContents()
            self.UI.content_tableWidget.horizontalHeader(
            ).setSectionResizeMode(QHeaderView.Stretch)  #自适应窗口

    #结果写入到输出文件
    def write_result(self):
        if self.UI.MCNP_radioButton.isChecked():
            self.to_MCNP()
        elif self.UI.RMC_radioButton.isChecked():
            self.to_RMC()

    def to_RMC(self):
        Componet_material = []
        Total_tad = 0
        library_mark = self.UI.lib_comboBox.currentText()  #获取lib_comboBox的内容
        b = self.UI.selected_listWidget.count()
        total_text = ''
        for i in range(0, self.UI.selected_listWidget.count()
                       ):  #获取selected_listWidget中的所有内容
            table_name = self.UI.selected_listWidget.item(i).text()
            ZAID, Nuclide_Name, Ion_Density = self.read_database(
                table_name, self.material_content[i])  #从数据库读取每个表中的数据
            Componet_material.append(table_name)
            Total_tad = Total_tad + eff_tad
            comment = [
                '        // ********************************************//',
                '        // ***      %s' % table_name,
                '        // ***  volume fraction [%] - {0}'.format(
                    self.material_content[i]),
                '        // ***  t.a.d. =  {:.5e}'.format(tad),
                '        // ***  eff.tad = {:.5e}'.format(eff_tad),
                '        // ********************************************//\n'
            ]
            text = '\n'.join(comment)
            #获取每种成分的数据
            for j in range(len(ZAID)):
                item = [
                    '        ', ZAID[j] + library_mark, Ion_Density[j], '//',
                    Nuclide_Name[j]
                ]
                line = ' '.join(item) + '\n'
                text = text + line
            #获取总的数据
            total_text = total_text + text
        num_componet = len(Componet_material)
        total_comment = [
            '//  --------------------------------------------------------------------',
            '//  Total has  {}  Componets material  '.format(num_componet),
            '//  Total eff t.a.d   =   {:.8e}'.format(Total_tad),
            '//  --------------------------------------------------------------------',
            '        density = {:.8e}'.format(Total_tad),
            '        @zaid.xxx        fraction\n'
        ]
        total_comment = '\n'.join(total_comment)
        output = total_comment + total_text
        path = os.getcwd() + '\output'
        folder = os.path.exists(path)
        if not folder:
            os.makedirs(path)
        else:
            pass
        save_dir = path + '\output.txt'
        with open(save_dir, 'w') as fou:
            fou.write(output)
            fou.close()

    def to_MCNP(self):
        Componet_material = []
        Total_tad = 0
        library_mark = self.UI.lib_comboBox.currentText()  #获取lib_comboBox的内容
        b = self.UI.selected_listWidget.count()
        total_text = ''
        for i in range(0, self.UI.selected_listWidget.count()
                       ):  #获取selected_listWidget中的所有内容
            table_name = self.UI.selected_listWidget.item(i).text()
            ZAID, Nuclide_Name, Ion_Density = self.read_database(
                table_name, self.material_content[i])  #从数据库读取每个表中的数据
            Componet_material.append(table_name)
            Total_tad = Total_tad + eff_tad
            comment = [
                'c ********************************************c',
                'c ***      %s' % table_name,
                'c ***  volume fraction [%] - {0}'.format(
                    self.material_content[i]),
                'c ***  t.a.d. =  {:.5e}'.format(tad),
                'c ***  eff.tad = {:.5e}'.format(eff_tad),
                'c ********************************************c\n'
            ]
            text = '\n'.join(comment)
            #获取每种成分的数据
            for j in range(len(ZAID)):
                item = [
                    '        ', ZAID[j] + library_mark, Ion_Density[j], '$',
                    Nuclide_Name[j]
                ]
                line = ' '.join(item) + '\n'
                text = text + line
            #获取总的数据
            total_text = total_text + text
        num_componet = len(Componet_material)
        total_comment = [
            'c  --------------------------------------------------------------------',
            'c  Total has  {}  Componets material  '.format(num_componet),
            'c  Total eff t.a.d   =   {:.8e}'.format(Total_tad),
            'c  --------------------------------------------------------------------\n'
        ]
        total_comment = '\n'.join(total_comment)
        output = total_comment + total_text
        path = os.getcwd() + '\output'
        folder = os.path.exists(path)
        if not folder:
            os.makedirs(path)
        else:
            pass
        save_dir = path + '\output.txt'
        with open(save_dir, 'w') as fou:
            fou.write(output)
            fou.close()

    #判断表是否在数据库中
    def if_exits_database(self, table_name):
        table_names = []
        conn = sqlite3.connect('data.db')
        cur = conn.cursor()
        sql = "SELECT name FROM sqlite_master WHERE type='table' order by name"
        cur.execute(sql)
        item = cur.fetchall()
        for lst in item:
            table_names.append(lst[0])
        cur.close()
        conn.commit()
        conn.close()
        if table_name in table_names:
            flag = True
        else:
            flag = False
        return flag

    #完成从数据库读取每个表中的数据
    def read_database(self, table_name, a=100):
        flag = self.if_exits_database(table_name)
        if flag:
            colume_frac = a
            global tad
            global eff_tad
            ZAID = []
            Nuclide_Name = []
            Ion_Density = []
            tad = 0
            eff_tad = 0
            #连接数据库,创建游标
            conn = sqlite3.connect('data.db')
            cur = conn.cursor()
            sql = 'SELECT * FROM %s' % table_name
            cursor = conn.execute(sql)
            for row in cursor:
                ZAID.append(row[0])
                Nuclide_Name.append(row[1])
                density = '{:.8e}'.format(row[2] * colume_frac /
                                          100)  #乘以体积份额计算考虑占空比后的核子密度
                Ion_Density.append(density)
                tad = row[2] + tad  #计算总核子密度
                eff_tad = row[2] * colume_frac / 100 + eff_tad  #计算材料总的有效核子密度
            data = [ZAID, Nuclide_Name, Ion_Density]  #每个表中的元素
            conn.close()
            return data
        else:
            self.warning_dlg('表不存在')

    def fresh(self):
        self.material_content = []
        self.UI.selected_listWidget.clear()
        self.UI.content_tableWidget.setColumnCount(0)  #清空content_tableWidget
        self.UI.content_tableWidget.setRowCount(0)
Пример #41
0
Файл: kline.py Проект: rainly/hq
 def drawBK(self):
     self.setAutoFillBackground(True)
     palette = QPalette()
     palette.setColor(QPalette.Background, QColor("#000000"))
     self.setPalette(palette)
Пример #42
0
class RenamingOptionsPage(OptionsPage):

    NAME = "filerenaming"
    TITLE = N_("File Naming")
    PARENT = None
    SORT_ORDER = 40
    ACTIVE = True

    options = [
        config.BoolOption("setting", "windows_compatibility", True),
        config.BoolOption("setting", "ascii_filenames", False),
        config.BoolOption("setting", "rename_files", False),
        config.TextOption(
            "setting",
            "file_naming_format",
            DEFAULT_FILE_NAMING_FORMAT,
        ),
        config.BoolOption("setting", "move_files", False),
        config.TextOption("setting", "move_files_to", _default_music_dir),
        config.BoolOption("setting", "move_additional_files", False),
        config.TextOption("setting", "move_additional_files_pattern",
                          "*.jpg *.png"),
        config.BoolOption("setting", "delete_empty_dirs", True),
    ]

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_RenamingOptionsPage()
        self.ui.setupUi(self)

        self.ui.ascii_filenames.clicked.connect(self.update_examples)
        self.ui.windows_compatibility.clicked.connect(self.update_examples)
        self.ui.rename_files.clicked.connect(self.update_examples)
        self.ui.move_files.clicked.connect(self.update_examples)
        self.ui.move_files_to.editingFinished.connect(self.update_examples)

        self.ui.move_files.toggled.connect(
            partial(enabledSlot, self.toggle_file_moving))
        self.ui.rename_files.toggled.connect(
            partial(enabledSlot, self.toggle_file_renaming))
        self.ui.file_naming_format.textChanged.connect(self.check_formats)
        self.ui.file_naming_format_default.clicked.connect(
            self.set_file_naming_format_default)
        self.highlighter = TaggerScriptSyntaxHighlighter(
            self.ui.file_naming_format.document())
        self.ui.move_files_to_browse.clicked.connect(self.move_files_to_browse)

        textEdit = self.ui.file_naming_format
        self.textEditPaletteNormal = textEdit.palette()
        self.textEditPaletteReadOnly = QPalette(self.textEditPaletteNormal)
        disabled_color = self.textEditPaletteNormal.color(
            QPalette.Inactive, QPalette.Window)
        self.textEditPaletteReadOnly.setColor(QPalette.Disabled, QPalette.Base,
                                              disabled_color)

    def toggle_file_moving(self, state):
        self.ui.delete_empty_dirs.setEnabled(state)
        self.ui.move_files_to.setEnabled(state)
        self.ui.move_files_to_browse.setEnabled(state)
        self.ui.move_additional_files.setEnabled(state)
        self.ui.move_additional_files_pattern.setEnabled(state)

    def toggle_file_renaming(self, state):

        self.ui.file_naming_format.setEnabled(state)
        self.ui.file_naming_format_default.setEnabled(state)
        self.ui.ascii_filenames.setEnabled(state)
        self.ui.file_naming_format_group.setEnabled(state)
        if not IS_WIN:
            self.ui.windows_compatibility.setEnabled(state)

        if self.ui.file_naming_format.isEnabled():
            self.ui.file_naming_format.setPalette(self.textEditPaletteNormal)
        else:
            self.ui.file_naming_format.setPalette(self.textEditPaletteReadOnly)

    def check_formats(self):
        self.test()
        self.update_examples()

    def _example_to_filename(self, file):
        settings = SettingsOverride(
            config.setting, {
                'ascii_filenames': self.ui.ascii_filenames.isChecked(),
                'file_naming_format': self.ui.file_naming_format.toPlainText(),
                'move_files': self.ui.move_files.isChecked(),
                'move_files_to': os.path.normpath(
                    self.ui.move_files_to.text()),
                'rename_files': self.ui.rename_files.isChecked(),
                'windows_compatibility':
                self.ui.windows_compatibility.isChecked(),
            })

        try:
            if config.setting["enable_tagger_scripts"]:
                for s_pos, s_name, s_enabled, s_text in config.setting[
                        "list_of_scripts"]:
                    if s_enabled and s_text:
                        parser = ScriptParser()
                        parser.eval(s_text, file.metadata)
            filename = file._make_filename(file.filename, file.metadata,
                                           settings)
            if not settings["move_files"]:
                return os.path.basename(filename)
            return filename
        except ScriptError:
            return ""
        except TypeError:
            return ""

    def update_examples(self):
        # TODO: Here should be more examples etc.
        # TODO: Would be nice to show diffs too....
        example1 = self._example_to_filename(self.example_1())
        example2 = self._example_to_filename(self.example_2())
        self.ui.example_filename.setText(example1)
        self.ui.example_filename_va.setText(example2)

    def load(self):
        if IS_WIN:
            self.ui.windows_compatibility.setChecked(True)
            self.ui.windows_compatibility.setEnabled(False)
        else:
            self.ui.windows_compatibility.setChecked(
                config.setting["windows_compatibility"])
        self.ui.rename_files.setChecked(config.setting["rename_files"])
        self.ui.move_files.setChecked(config.setting["move_files"])
        self.ui.ascii_filenames.setChecked(config.setting["ascii_filenames"])
        self.ui.file_naming_format.setPlainText(
            config.setting["file_naming_format"])
        args = {
            "picard-doc-scripting-url": PICARD_URLS['doc_scripting'],
        }
        text = _('<a href="%(picard-doc-scripting-url)s">Open Scripting'
                 ' Documentation in your browser</a>') % args
        self.ui.file_naming_format_documentation.setText(text)
        self.ui.move_files_to.setText(config.setting["move_files_to"])
        self.ui.move_files_to.setCursorPosition(0)
        self.ui.move_additional_files.setChecked(
            config.setting["move_additional_files"])
        self.ui.move_additional_files_pattern.setText(
            config.setting["move_additional_files_pattern"])
        self.ui.delete_empty_dirs.setChecked(
            config.setting["delete_empty_dirs"])
        self.update_examples()

    def check(self):
        self.check_format()
        if self.ui.move_files.isChecked(
        ) and not self.ui.move_files_to.text().strip():
            raise OptionsCheckError(
                _("Error"),
                _("The location to move files to must not be empty."))

    def check_format(self):
        parser = ScriptParser()
        try:
            parser.eval(self.ui.file_naming_format.toPlainText())
        except Exception as e:
            raise OptionsCheckError("", str(e))
        if self.ui.rename_files.isChecked():
            if not self.ui.file_naming_format.toPlainText().strip():
                raise OptionsCheckError(
                    "", _("The file naming format must not be empty."))

    def save(self):
        config.setting[
            "windows_compatibility"] = self.ui.windows_compatibility.isChecked(
            )
        config.setting["ascii_filenames"] = self.ui.ascii_filenames.isChecked()
        config.setting["rename_files"] = self.ui.rename_files.isChecked()
        config.setting[
            "file_naming_format"] = self.ui.file_naming_format.toPlainText()
        self.tagger.window.enable_renaming_action.setChecked(
            config.setting["rename_files"])
        config.setting["move_files"] = self.ui.move_files.isChecked()
        config.setting["move_files_to"] = os.path.normpath(
            self.ui.move_files_to.text())
        config.setting[
            "move_additional_files"] = self.ui.move_additional_files.isChecked(
            )
        config.setting[
            "move_additional_files_pattern"] = self.ui.move_additional_files_pattern.text(
            )
        config.setting[
            "delete_empty_dirs"] = self.ui.delete_empty_dirs.isChecked()
        self.tagger.window.enable_moving_action.setChecked(
            config.setting["move_files"])

    def display_error(self, error):
        pass

    def set_file_naming_format_default(self):
        self.ui.file_naming_format.setText(self.options[3].default)


#        self.ui.file_naming_format.setCursorPosition(0)

    def example_1(self):
        file = File("ticket_to_ride.mp3")
        file.state = File.NORMAL
        file.metadata['album'] = 'Help!'
        file.metadata['title'] = 'Ticket to Ride'
        file.metadata['artist'] = 'The Beatles'
        file.metadata['artistsort'] = 'Beatles, The'
        file.metadata['albumartist'] = 'The Beatles'
        file.metadata['albumartistsort'] = 'Beatles, The'
        file.metadata['tracknumber'] = '7'
        file.metadata['totaltracks'] = '14'
        file.metadata['discnumber'] = '1'
        file.metadata['totaldiscs'] = '1'
        file.metadata['date'] = '1965-08-06'
        file.metadata['releasetype'] = ['album', 'soundtrack']
        file.metadata['~primaryreleasetype'] = ['album']
        file.metadata['~secondaryreleasetype'] = ['soundtrack']
        file.metadata['releasestatus'] = 'official'
        file.metadata['releasecountry'] = 'US'
        file.metadata['~extension'] = 'mp3'
        file.metadata[
            'musicbrainz_albumid'] = '2c053984-4645-4699-9474-d2c35c227028'
        file.metadata[
            'musicbrainz_albumartistid'] = 'b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d'
        file.metadata[
            'musicbrainz_artistid'] = 'b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d'
        file.metadata[
            'musicbrainz_recordingid'] = 'ed052ae1-c950-47f2-8d2b-46e1b58ab76c'
        file.metadata[
            'musicbrainz_releasetrackid'] = '7668a62a-2fac-3151-a744-5707ac8c883c'
        return file

    def example_2(self):
        file = File("track05.mp3")
        file.state = File.NORMAL
        file.metadata['album'] = "Coup d'État, Volume 1: Ku De Ta / Prologue"
        file.metadata['title'] = "I've Got to Learn the Mambo"
        file.metadata['artist'] = "Snowboy feat. James Hunter"
        file.metadata['artistsort'] = "Snowboy feat. Hunter, James"
        file.metadata['albumartist'] = config.setting['va_name']
        file.metadata['albumartistsort'] = config.setting['va_name']
        file.metadata['tracknumber'] = '5'
        file.metadata['totaltracks'] = '13'
        file.metadata['discnumber'] = '2'
        file.metadata['totaldiscs'] = '2'
        file.metadata['discsubtitle'] = "Beat Up"
        file.metadata['date'] = '2005-07-04'
        file.metadata['releasetype'] = ['album', 'compilation']
        file.metadata['~primaryreleasetype'] = 'album'
        file.metadata['~secondaryreleasetype'] = 'compilation'
        file.metadata['releasestatus'] = 'official'
        file.metadata['releasecountry'] = 'AU'
        file.metadata['compilation'] = '1'
        file.metadata['~multiartist'] = '1'
        file.metadata['~extension'] = 'mp3'
        file.metadata[
            'musicbrainz_albumid'] = '4b50c71e-0a07-46ac-82e4-cb85dc0c9bdd'
        file.metadata[
            'musicbrainz_recordingid'] = 'b3c487cb-0e55-477d-8df3-01ec6590f099'
        file.metadata[
            'musicbrainz_releasetrackid'] = 'f8649a05-da39-39ba-957c-7abf8f9012be'
        file.metadata[
            'musicbrainz_albumartistid'] = '89ad4ac3-39f7-470e-963a-56509c546377'
        file.metadata['musicbrainz_artistid'] = [
            '7b593455-d207-482c-8c6f-19ce22c94679',
            '9e082466-2390-40d1-891e-4803531f43fd'
        ]
        return file

    def move_files_to_browse(self):
        path = QtWidgets.QFileDialog.getExistingDirectory(
            self, "", self.ui.move_files_to.text())
        if path:
            path = os.path.normpath(path)
            self.ui.move_files_to.setText(path)

    def test(self):
        self.ui.renaming_error.setStyleSheet("")
        self.ui.renaming_error.setText("")
        try:
            self.check_format()
        except OptionsCheckError as e:
            self.ui.renaming_error.setStyleSheet(self.STYLESHEET_ERROR)
            self.ui.renaming_error.setText(e.info)
            return
Пример #43
0
def main():
    app = QApplication(sys.argv)

    # set SUPERIOR dark theme
    app.setStyle('Fusion')
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(15, 15, 15))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)

    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Highlight, QColor(142, 45, 197).lighter())
    palette.setColor(QPalette.HighlightedText, Qt.black)

    app.setPalette(palette)
    Window()
    sys.exit(app.exec_())
Пример #44
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1194, 793)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        #self.mainLayout = QtWidgets.QGridLayout(self)

        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.blue)  # 设置字体颜色
        pe.setColor(QPalette.Window, Qt.darkGray)  # 设置背景颜色

        self.label_name = QtWidgets.QLabel(self.centralwidget)
        self.label_name.setGeometry(QtCore.QRect(10, 30, 250, 30))
        self.label_name.setObjectName("label_name")
        self.label_name.setFont(QFont("Roman times", 25, QFont.Bold))

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 90, 250,
                                            100))  #(, 上边高度, 右边长度, 下边高度,)
        self.label.setObjectName("label")
        self.label.setFont(QFont("Roman times", 30, QFont.Bold))
        self.label.setAutoFillBackground(True)  # 设置背景充满,为设置背景颜色的必要条件
        self.label.setPalette(pe)

        self.label_status = QtWidgets.QLabel(self.centralwidget)
        self.label_status.setGeometry(QtCore.QRect(
            280, 90, 400, 100))  #(, 上边高度, 右边长度, 下边高度,)
        self.label_status.setObjectName("label")
        self.label_status.setFont(QFont("Calibri", 30, QFont.Bold))

        self.Normal_Test_Button = QtWidgets.QPushButton(self.centralwidget)
        self.Normal_Test_Button.setGeometry(QtCore.QRect(480, 30, 91, 31))
        self.Normal_Test_Button.setObjectName("pushButton")

        self.Offline_Test_Button = QtWidgets.QPushButton(self.centralwidget)
        self.Offline_Test_Button.setGeometry(QtCore.QRect(480, 80, 91, 31))
        self.Offline_Test_Button.setObjectName("pushButton_2")

        self.Loop_Test_Button = QtWidgets.QPushButton(self.centralwidget)
        self.Loop_Test_Button.setGeometry(QtCore.QRect(480, 130, 91, 31))
        self.Loop_Test_Button.setObjectName("pushButton_3")

        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(10, 190, 451, 41))
        self.lineEdit.setObjectName("lineEdit")

        self.Start_Button = QtWidgets.QPushButton(self.centralwidget)
        self.Start_Button.setGeometry(QtCore.QRect(480, 190, 91, 31))
        self.Start_Button.setObjectName("pushButton_4")

        self.Attributes = QtWidgets.QTableView(self.centralwidget)
        self.Attributes.setGeometry(QtCore.QRect(660, 130, 521, 101))
        self.Attributes.setObjectName("Attributes")

        self.Test_Item = MyTable(self.centralwidget)
        self.Test_Item.setGeometry(QtCore.QRect(10, 250, 1171, 491))
        self.Test_Item.setObjectName("Test_Item")

        self.label_time = ShowTime(self.centralwidget)
        self.label_time.setGeometry(QtCore.QRect(800, 20, 1000, 71))
        self.label_time.setObjectName("label_time")

        # self.label_3 = QtWidgets.QLabel(self.centralwidget)
        # self.label_3.setGeometry(QtCore.QRect(660, 10, 51, 31))
        # self.label_3.setObjectName("label_3")
        #
        # self.label_4 = QtWidgets.QLabel(self.centralwidget)
        # self.label_4.setGeometry(QtCore.QRect(660, 50, 51, 31))
        # self.label_4.setObjectName("label_4")
        #
        # self.label_5 = QtWidgets.QLabel(self.centralwidget)
        # self.label_5.setGeometry(QtCore.QRect(660, 90, 51, 31))
        # self.label_5.setObjectName("label_5")

        # self.pass_num = QtWidgets.QTableView(self.centralwidget)
        # self.pass_num.setGeometry(QtCore.QRect(720, 20, 161, 21))
        # self.pass_num.setObjectName("Attributes_2")
        #
        # self.fail_num = QtWidgets.QTableView(self.centralwidget)
        # self.fail_num.setGeometry(QtCore.QRect(720, 60, 161, 21))
        # self.fail_num.setObjectName("Attributes_3")
        #
        # self.total_num = QtWidgets.QTableView(self.centralwidget)
        # self.total_num.setGeometry(QtCore.QRect(720, 90, 161, 21))
        # self.total_num.setObjectName("Attributes_4")

        MainWindow.setCentralWidget(self.centralwidget)

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1194, 22))
        self.menubar.setObjectName("menubar")

        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Пример #45
0
 def set_background_color(self):
     """Sets the background color of the main window."""
     palette = QPalette()
     palette.setColor(QPalette.Background, Qt.white)
     self.setPalette(palette)
Пример #46
0
    def __init__(self, fomod_root):
        self.root = Path(fomod_root)
        self.installer = pyfomod.Installer(self.root)

        self.app = QApplication([])
        self.app.setStyle('Fusion')
        dark_palette = QPalette()
        dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.WindowText, Qt.white)
        dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
        dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
        dark_palette.setColor(QPalette.ToolTipText, Qt.white)
        dark_palette.setColor(QPalette.Text, Qt.white)
        dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ButtonText, Qt.white)
        dark_palette.setColor(QPalette.BrightText, Qt.red)
        dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.HighlightedText, Qt.black)
        self.app.setPalette(dark_palette)
        self.app.setStyleSheet('''
            QToolTip {
                color: #ffffff;
                background-color: #2a82da;
                border: 1px solid white;
            }
        ''')
        super().__init__()
        uic.loadUi(UI_FILE, self)

        # load the gui
        self.show()
        self.ensure_gui_elements()
        self.apply_initial_sizes()
        self.setup_signal_handlers()
        self.initial_render()
Пример #47
0
    def paintEvent(self, evt):
        """
        Protected method handling paint events.
        
        @param evt paint event (QPaintEvent)
        """
        if self.__grabbing:  # grabWindow() should just get the background
            return

        painter = QPainter(self)
        pal = QPalette(QToolTip.palette())
        font = QToolTip.font()

        handleColor = pal.color(QPalette.Active, QPalette.Highlight)
        handleColor.setAlpha(160)
        overlayColor = QColor(0, 0, 0, 160)
        textColor = pal.color(QPalette.Active, QPalette.Text)
        textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
        painter.drawPixmap(0, 0, self.__pixmap)
        painter.setFont(font)

        r = QRect(self.__selection)
        if not self.__selection.isNull():
            grey = QRegion(self.rect())
            if self.__mode == SnapshotRegionGrabber.Ellipse:
                reg = QRegion(r, QRegion.Ellipse)
            else:
                reg = QRegion(r)
            grey = grey.subtracted(reg)
            painter.setClipRegion(grey)
            painter.setPen(Qt.NoPen)
            painter.setBrush(overlayColor)
            painter.drawRect(self.rect())
            painter.setClipRect(self.rect())
            drawRect(painter, r, handleColor)

        if self.__showHelp:
            painter.setPen(textColor)
            painter.setBrush(textBackgroundColor)
            self.__helpTextRect = painter.boundingRect(
                self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap,
                self.__helpText).translated(-self.__desktop.x(),
                                            -self.__desktop.y())
            self.__helpTextRect.adjust(-2, -2, 4, 2)
            drawRect(painter, self.__helpTextRect, textColor,
                     textBackgroundColor)
            painter.drawText(self.__helpTextRect.adjusted(3, 3, -3, -3),
                             Qt.TextWordWrap, self.__helpText)

        if self.__selection.isNull():
            return

        # The grabbed region is everything which is covered by the drawn
        # rectangles (border included). This means that there is no 0px
        # selection, since a 0px wide rectangle will always be drawn as a line.
        txt = "{0:n}, {1:n} ({2:n} x {3:n})".format(self.__selection.x(),
                                                    self.__selection.y(),
                                                    self.__selection.width(),
                                                    self.__selection.height())
        textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
        boundingRect = textRect.adjusted(-4, 0, 0, 0)

        if textRect.width() < r.width() - 2 * self.__handleSize and \
           textRect.height() < r.height() - 2 * self.__handleSize and \
           r.width() > 100 and \
           r.height() > 100:
            # center, unsuitable for small selections
            boundingRect.moveCenter(r.center())
            textRect.moveCenter(r.center())
        elif r.y() - 3 > textRect.height() and \
                r.x() + textRect.width() < self.rect().width():
            # on top, left aligned
            boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3))
            textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3))
        elif r.x() - 3 > textRect.width():
            # left, top aligned
            boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()))
            textRect.moveTopRight(QPoint(r.x() - 5, r.y()))
        elif r.bottom() + 3 + textRect.height() < self.rect().bottom() and \
                r.right() > textRect.width():
            # at bottom, right aligned
            boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3))
            textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3))
        elif r.right() + textRect.width() + 3 < self.rect().width():
            # right, bottom aligned
            boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()))
            textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()))

        # If the above didn't catch it, you are running on a very
        # tiny screen...
        drawRect(painter, boundingRect, textColor, textBackgroundColor)
        painter.drawText(textRect, Qt.AlignHCenter, txt)

        if (r.height() > self.__handleSize * 2 and
            r.width() > self.__handleSize * 2) or \
           not self.__mouseDown:
            self.__updateHandles()
            painter.setPen(Qt.NoPen)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.StrokeMask))
            painter.drawRect(self.rect())
            handleColor.setAlpha(60)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.FillMask))
            painter.drawRect(self.rect())
Пример #48
0
def main():
    fix_windows_stdout_stderr()

    if sys.version_info < (3, 4):
        print("You need at least Python 3.4 for this application!")
        sys.exit(1)

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(os.path.realpath(urh_exe)), "..", "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith("/usr") and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed -> add directory to path
        sys.path.insert(0, src_dir)

    if len(sys.argv) > 1 and sys.argv[1] == "--version":
        import urh.version
        print(urh.version.VERSION)
        sys.exit(0)

    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            sys.path.insert(0, os.path.join(prefix))
            from data import generate_ui
            generate_ui.gen()
        except (ImportError, FileNotFoundError):
            # The generate UI script cannot be found so we are most likely in release mode, no problem here.
            pass

    from urh.util import util
    util.set_shared_library_path()

    try:
        import urh.cythonext.signal_functions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        if hasattr(sys, "frozen"):
            print("C++ Extensions not found. Exiting...")
            sys.exit(1)
        print("Could not find C++ extensions, trying to build them.")
        old_dir = os.path.realpath(os.curdir)
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(["URH"] + sys.argv[1:])
    app.setWindowIcon(QIcon(":/icons/icons/appicon.png"))

    util.set_icon_theme()

    font_size = constants.SETTINGS.value("font_size", 0, int)
    if font_size > 0:
        font = app.font()
        font.setPointSize(font_size)
        app.setFont(font)

    constants.SETTINGS.setValue("default_theme", app.style().objectName())

    if constants.SETTINGS.value("theme_index", 0, int) > 0:
        app.setStyle(QStyleFactory.create("Fusion"))

        if constants.SETTINGS.value("theme_index", 0, int) == 2:
            palette = QPalette()
            background_color = QColor(56, 60, 74)
            text_color = QColor(211, 218, 227).lighter()
            palette.setColor(QPalette.Window, background_color)
            palette.setColor(QPalette.WindowText, text_color)
            palette.setColor(QPalette.Base, background_color)
            palette.setColor(QPalette.AlternateBase, background_color)
            palette.setColor(QPalette.ToolTipBase, background_color)
            palette.setColor(QPalette.ToolTipText, text_color)
            palette.setColor(QPalette.Text, text_color)

            palette.setColor(QPalette.Button, background_color)
            palette.setColor(QPalette.ButtonText, text_color)

            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            palette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.darkGray)

            palette.setColor(QPalette.Highlight, QColor(200, 50, 0))
            palette.setColor(QPalette.HighlightedText, text_color)
            app.setPalette(palette)

    # use system colors for painting
    widget = QWidget()
    bg_color = widget.palette().color(QPalette.Background)
    fg_color = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bg_color
    constants.LINECOLOR = fg_color
    constants.SELECTION_COLOR = selection_color
    constants.SEND_INDICATOR_COLOR = selection_color

    main_window = MainController()
    import multiprocessing as mp
    # allow usage of prange (OpenMP) in Processes
    mp.set_start_method("spawn")

    if sys.platform == "darwin":
        menu_bar = main_window.menuBar()
        menu_bar.setNativeMenuBar(False)
    elif sys.platform == "win32":
        # Ensure we get the app icon in windows taskbar
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("jopohl.urh")
        import multiprocessing as mp
        mp.freeze_support()

    main_window.showMaximized()
    # main_window.setFixedSize(1920, 1080 - 30)  # Youtube

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    return_code = app.exec_()
    app.closeAllWindows()
    os._exit(return_code)  # sys.exit() is not enough on Windows and will result in crash on exit
Пример #49
0
class SkinAssets(GWAssets):
    """
    Handles the overall look and feel of an application.

    The colors loaded from the [Skin] section will be restricted to the
    QPalette properties.

    If you pass in an existing custom color map, then the colors loaded from
    the [Custom] section will be restricted to the keywords named.
    Otherwise, all of the keywords in the section will be assumed valid.
    custom_color_map = {
        "treewordcount": (0,0,0),
        "statusnone": (0,0,0),
        "statusunsaved": (0,0,0),
        "statussaved": (0,0,0)
        }
    """
    def __init__(self,
                 asset_path: Union[Path, str],
                 custom_color_map: Optional[Dict[str, tuple]] = None):
        super().__init__(asset_path)
        self.theme_structure = ThemeStructure.SKIN
        self.skin_meta: ThemeMetaData = None
        self.conf_name = "skin.conf"
        self.custom_color_map = custom_color_map
        self.css_name = "style.qss"
        self.qt_gui_palette = QPalette()
        self.skin_list = [x for x in self.themes().keys()]
        self.skin_list.insert(0, "default")
        self.current_skin = 0

    def connect_on_change(self, callback):
        self.on_change = callback

    def apply_qss(self):
        """
        """
        css_data = SKIN_QSS
        if self.theme_name and self.css_name:
            self.css_file = self.asset_path / self.theme_name / self.css_name
            try:
                if self.css_file.is_file():
                    with self.css_file.open(mode="r",
                                            encoding="utf8") as inFile:
                        css_data += inFile.read()
            except Exception as e:
                LOG.error(f"Could not load theme CSS file {e}")
                return
        qApp.setStyleSheet(css_data)

    def apply_theme(self):
        """
        Note: Call themes() and set_theme() before calling apply_theme().
        """
        # self.apply_qss()

        self.qt_gui_palette = QApplication.style().standardPalette()
        if self.theme_name == "default":
            qApp.setPalette(self.qt_gui_palette)
            return

        self.skin_meta: ThemeMetaData = self.themes()[self.theme_name]
        skin_file = Path(self.skin_meta.filename)
        if self.skin_meta.filename.endswith(".yaml"):
            with skin_file.open("r") as f:
                base16 = yaml.load(f.read())
            self._qt_palette_per_base16(base16)
        else:
            parser = GWConfigParser()
            parser.parse_file(skin_file)

            base16 = {}
            # We'll load the Base16 section first (if there is one), because the
            # Skin section can refer to the base16 definitions.
            section = "Base16"
            if parser.has_section(section):
                for option, _ in parser.items(section):
                    base16[option] = parser[section].getqcolor(option)
                if len(base16) != 16:
                    raise GruntWurkConfigError(
                        f"Expected 16 colors in the [Base16] section but only found {len(base16)}."
                    )
                self._qt_palette_per_base16(base16)

            section = "Skin"
            if parser.has_section(section):
                for option in parser.items(section):
                    if option not in QPALETTE_SLUGS:
                        LOG.warning(
                            f"Skin theme '{self.theme_name}' refers to an element '{option}' that doesn't exist."
                        )
                self._qt_palette_per_conf(section, parser, base16)

            section = "Custom"
            if parser.has_section(section):
                for option in parser.items(section):
                    if option not in self.custom_color_map:
                        LOG.warning(
                            f"Skin theme {self.theme_name} refers to an custom color '{option}' that doesn't exist."
                        )
                    else:
                        self.custom_color_map[option] = parser[
                            section].getcolor(option)

        LOG.info(f"Loaded skin theme '{self.theme_name}'")
        qApp.setPalette(self.qt_gui_palette)

    def _qt_palette_per_conf(self, parser, base16):
        def color_choice(section, option, default) -> QColor:
            c = str(parser[section].gettext(option)).lower()
            if re.match(r"base0[0-9a-f]", c):
                color = base16[option]
                if isinstance(color, QColor):
                    return color
                return QColor(f"#{color}")
            return parser[section].getqcolor(option, default)

        pal = self.qt_gui_palette
        pal.setColor(QPalette.Window, color_choice("window", pal.window))
        pal.setColor(QPalette.WindowText,
                     color_choice("windowtext", pal.windowText))
        pal.setColor(QPalette.Base, color_choice("base", pal.base))
        pal.setColor(QPalette.AlternateBase,
                     color_choice("alternatebase", pal.alternateBase))
        pal.setColor(QPalette.Text, color_choice("text", pal.text))
        pal.setColor(QPalette.ToolTipBase,
                     color_choice("tooltipbase", pal.toolTipBase))
        pal.setColor(QPalette.ToolTipText,
                     color_choice("tooltiptext", pal.toolTipText))
        pal.setColor(QPalette.Button, color_choice("button", pal.button))
        pal.setColor(QPalette.ButtonText,
                     color_choice("buttontext", pal.buttonText))
        pal.setColor(QPalette.BrightText,
                     color_choice("brighttext", pal.brightText))
        pal.setColor(QPalette.Highlight,
                     color_choice("highlight", pal.highlight))
        pal.setColor(QPalette.HighlightedText,
                     color_choice("highlightedtext", pal.highlightedText))
        pal.setColor(QPalette.Link, color_choice("link", pal.link))
        pal.setColor(QPalette.LinkVisited,
                     color_choice("linkvisited", pal.linkVisited))
        pal.setColor(QPalette.PlaceholderText,
                     color_choice("placeholdertext", pal.placeholderText))
        pal.setColor(QPalette.Light, color_choice("light", pal.light))
        pal.setColor(QPalette.Midlight, color_choice("midlight", pal.midlight))
        pal.setColor(QPalette.Dark, color_choice("dark", pal.dark))
        pal.setColor(QPalette.Mid, color_choice("mid", pal.mid))
        pal.setColor(QPalette.Shadow, color_choice("shadow", pal.shadow))

    def _qt_palette_per_base16(self, base16):
        for base_number in base16.keys():
            if (not base_number.startswith('base0')) or isinstance(
                    base16[base_number], QColor):
                continue
            base16[base_number] = QColor(f"#{base16[base_number]}")

        pal = self.qt_gui_palette
        pal.setColor(QPalette.Window, base16[QPALETTE_SLUGS["window"]])
        pal.setColor(QPalette.WindowText, base16[QPALETTE_SLUGS["windowtext"]])
        pal.setColor(QPalette.Base, base16[QPALETTE_SLUGS["base"]])
        pal.setColor(QPalette.AlternateBase,
                     base16[QPALETTE_SLUGS["alternatebase"]])
        pal.setColor(QPalette.Text, base16[QPALETTE_SLUGS["text"]])
        pal.setColor(QPalette.ToolTipBase,
                     base16[QPALETTE_SLUGS["tooltipbase"]])
        pal.setColor(QPalette.ToolTipText,
                     base16[QPALETTE_SLUGS["tooltiptext"]])
        pal.setColor(QPalette.Button, base16[QPALETTE_SLUGS["button"]])
        pal.setColor(QPalette.ButtonText, base16[QPALETTE_SLUGS["buttontext"]])
        pal.setColor(QPalette.BrightText, base16[QPALETTE_SLUGS["brighttext"]])
        pal.setColor(QPalette.Highlight, base16[QPALETTE_SLUGS["highlight"]])
        pal.setColor(QPalette.HighlightedText,
                     base16[QPALETTE_SLUGS["highlightedtext"]])
        pal.setColor(QPalette.Link, base16[QPALETTE_SLUGS["link"]])
        pal.setColor(QPalette.LinkVisited,
                     base16[QPALETTE_SLUGS["linkvisited"]])
        pal.setColor(QPalette.PlaceholderText,
                     base16[QPALETTE_SLUGS["placeholdertext"]])
        pal.setColor(QPalette.Light, base16[QPALETTE_SLUGS["light"]])
        pal.setColor(QPalette.Midlight, base16[QPALETTE_SLUGS["midlight"]])
        pal.setColor(QPalette.Dark, base16[QPALETTE_SLUGS["dark"]])
        pal.setColor(QPalette.Mid, base16[QPALETTE_SLUGS["mid"]])
        pal.setColor(QPalette.Shadow, base16[QPALETTE_SLUGS["shadow"]])

    def _cycle_skin(self, increment=1):
        self.current_skin = next_in_range(self.current_skin, increment,
                                          len(self.skin_list) - 1)
        theme_name = self.skin_list[self.current_skin]
        self.set_theme(theme_name)
        self.apply_theme()
        self.apply_qss()
        if self.on_change:
            self.on_change(self.qt_gui_palette.color(QPalette.BrightText))
        qApp.activeWindow().statusBar().showMessage(
            f"Now using the '{theme_name}' skin.")

    def next_skin(self):
        self._cycle_skin(1)

    def previous_skin(self):
        self._cycle_skin(-1)
Пример #50
0
    def switch_theme(self, theme):
        if theme == "dark":
            DARK_GREY = QColor(53, 53, 53)

            dark_p = QPalette()

            dark_p.setColor(QPalette.Window, DARK_GREY)
            dark_p.setColor(QPalette.WindowText, Qt.white)
            dark_p.setColor(QPalette.Base, QColor(25, 25, 25))
            dark_p.setColor(QPalette.AlternateBase, DARK_GREY)
            dark_p.setColor(QPalette.ToolTipBase, DARK_GREY)
            dark_p.setColor(QPalette.ToolTipText, Qt.white)
            dark_p.setColor(QPalette.Text, Qt.white)
            dark_p.setColor(QPalette.Button, DARK_GREY)
            dark_p.setColor(QPalette.ButtonText, Qt.white)
            dark_p.setColor(QPalette.BrightText, Qt.red)
            dark_p.setColor(QPalette.Highlight, ACCENT_COLOR)
            # this coloring was found to be harmful as the "inactive" state was
            # getting set and showing the wrong colors at the wrong times.
            # dark_p.setColor(QPalette.Inactive, QPalette.Highlight, Qt.lightGray)
            dark_p.setColor(QPalette.HighlightedText, Qt.black)
            dark_p.setColor(QPalette.Disabled, QPalette.Text, Qt.darkGray)
            dark_p.setColor(QPalette.Disabled, QPalette.ButtonText,
                            Qt.darkGray)
            dark_p.setColor(QPalette.Disabled, QPalette.Highlight, Qt.darkGray)
            dark_p.setColor(QPalette.Disabled, QPalette.Base, DARK_GREY)
            dark_p.setColor(QPalette.Link, ACCENT_COLOR)
            dark_p.setColor(QPalette.LinkVisited, ACCENT_COLOR)

            # the `bigButton` class is necessary because qt (or the fusion
            # style, not sure which) is putting a *gradient* on the buttons by
            # by default. Kind of crazy if you ask me, but it does make the
            # small buttons look good, so I only want to change it to a flat
            # color for larger buttons (and also round their corners because
            # large buttons don't look so good when they're blocky)

            # the QListWidget border removal is because it clashes with the
            # border we're drawing around our SelectableLoadables and the ui
            # looks too busy with that many borders

            self.app.setPalette(dark_p)
            self.app.setStyleSheet("""
                QToolTip {
                    color: #ffffff;
                    background-color: #2a2a2a;
                    border: 1px solid white;
                }
                QPushButton#bigButton {
                    background-color: rgb(64, 64, 64);
                    padding: 4px;
                    border: 1px solid rgb(25, 25, 25);
                    border-radius: 15%;
                }
                QPushButton#bigButton:hover {
                    background-color: rgb(67, 67, 67);
                }
                QPushButton#bigButton:pressed {
                    background-color: rgb(61, 61, 61);
                }
                QPushButton#backButton {
                    margin-top: 5px;
                    margin-left: 10px;
                }
                QLabel {
                    font-weight: Normal;
                }
                QTextEdit {
                    background-color: #212121;
                }
                SelectableLoadable, DragWidget, ReplayMapVis {
                    border: 1.5px solid rgb(32, 32, 32);
                }
                ReplayMapCreation {
                    border: 1.5px solid #1f1f1f;
                }
                QListWidget {
                    background-color: rgb(53, 53, 53);
                    QListWidget
                }
                """)
        else:
            self.app.setPalette(self.app.style().standardPalette())
            updated_palette = QPalette()
            # fixes inactive items not being greyed out
            updated_palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                                     Qt.darkGray)
            updated_palette.setColor(QPalette.Highlight, ACCENT_COLOR)
            updated_palette.setColor(QPalette.Disabled, QPalette.Highlight,
                                     Qt.darkGray)
            updated_palette.setColor(QPalette.Inactive, QPalette.Highlight,
                                     Qt.darkGray)
            updated_palette.setColor(QPalette.Link, ACCENT_COLOR)
            updated_palette.setColor(QPalette.LinkVisited, ACCENT_COLOR)
            self.app.setPalette(updated_palette)
            self.app.setStyleSheet("""
                QToolTip {
                    color: #000000;
                    background-color: #D5D5D5;
                    border: 1px solid white;
                }
                QPushButton#backButton {
                    margin-top: 5px;
                    margin-left: 10px;
                }
                QLabel {
                    font-weight: Normal;
                }
                LoadableW, CheckW, DragWidget {
                    border: 1.5px solid #bfbfbf;
                }
                """)
Пример #51
0
    def SetDarkMode(self):
        C1 = 22

        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(53, 53, 53))
        palette.setColor(QPalette.WindowText, Qt.white)
        palette.setColor(QPalette.Base, QColor(25, 25, 25))
        palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        palette.setColor(QPalette.ToolTipBase, Qt.white)
        palette.setColor(QPalette.ToolTipText, Qt.white)
        palette.setColor(QPalette.Text, Qt.white)
        palette.setColor(QPalette.Button, QColor(53, 53, 53))
        palette.setColor(QPalette.ButtonText, Qt.white)
        palette.setColor(QPalette.BrightText, Qt.red)
        palette.setColor(QPalette.Link, QColor(42, 130, 218))
        palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        palette.setColor(QPalette.HighlightedText, Qt.black)

        self.Dialog.setPalette(palette)
Пример #52
0
    def __init__(self, parent=None):
        #Parte de intefaz grafica
        super().__init__(parent)

        self.color = QColor(0, 0, 0, 0.5)
        self.setGeometry(550, 100, 1500, 500)
        self.pallette = QPalette(self.color)
        self.pallette.setColor(QPalette.Text, Qt.cyan)

        self.titulo_ventana = "ENVIO DE CORREO PARA HACER SPAM"
        self.setWindowTitle(self.titulo_ventana)
        self.setStyleSheet(
            "border-color: cyan; border-style: dashed; border-width: 2px; color:white"
        )
        self.setPalette(self.pallette)
        self.checkbox_opcion_spam_uno_a_uno = QCheckBox(
            "REALIZAR SPAM UNO A UN CORREO")
        self.checkbox_opcion_spam_uno_a_uno.clicked.connect(
            self.spam_uno_a_uno)
        self.checkbox_opcion_spam_uno_a_varios = QCheckBox(
            "REALIZAR SPAM UNO A VARIOS COOREOS")
        self.checkbox_opcion_spam_uno_a_varios.clicked.connect(
            self.spam_uno_a_varios)

        self.label_user_email = QLabel("Ingresa tu direccion de correo: ")
        self.label_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_email.setStyleSheet("color: white")

        self.line_edit_user_email = QLineEdit(self)
        self.line_edit_user_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_email.setStyleSheet("color : black")

        self.label_user_password = QLabel("Ingresa tu password de correo")
        self.label_user_password.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_password.setStyleSheet("color: white")

        self.line_edit_user_password = QLineEdit(self)
        self.line_edit_user_password.setPlaceholderText(
            "Ingresa tu password de tu correo:")
        self.line_edit_user_password.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_password.setStyleSheet("color : black")

        self.label_victima_email = QLabel(
            "Ingresa direccion de correo destinatario: ")
        self.label_victima_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_victima_email.setStyleSheet("color: white")

        self.line_edit_victima_email = QLineEdit(self)
        self.line_edit_victima_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_victima_email.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_victima_email.setStyleSheet("color : black")

        self.label_user_asunto = QLabel("Ingresa el asunto ")
        self.label_user_asunto.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_asunto.setStyleSheet("color: white")

        self.line_edit_user_asunto = QLineEdit(self)
        self.line_edit_user_asunto.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_asunto.setFont(QFont("Times", 14, QFont.Bold,
                                                 True))
        self.line_edit_user_asunto.setStyleSheet("color : black")

        self.pushbutton_enviar = QPushButton("ENVIAR SPAM")
        self.pushbutton_enviar.setFont(QFont("Times", 14, QFont.Bold, True))
        self.pushbutton_enviar.setPalette(self.pallette)

        self.label_estado_proceso = QLabel("")
        self.label_estado_proceso.setText("ESPERANDO DATOS....")

        self.label_proceso = QLabel("Estado verificacion email y password")
        self.label_proceso_verificacion = QLabel("")
        self.label_proceso2 = QLabel(
            "Estado verificacion arroba de email origen y destino")
        self.label_proceso_verificacion2 = QLabel("")
        self.label_proceso3 = QLabel(
            "Estado verificacion terminacion correo origen y destino")
        self.label_proceso_verificacion3 = QLabel("")
        self.combobox_dominios_from = QComboBox()
        self.combobox_dominios_from.addItem("Gmail.com")
        self.combobox_dominios_from.insertSeparator(1)
        self.combobox_dominios_from.addItem("Outlook.com")
        self.combobox_dominios_from.addItem("Outlook.es")
        self.combobox_dominios_from.insertSeparator(4)
        self.combobox_dominios_from.addItem("Hotmail.com")
        self.combobox_dominios_from.addItem("Hotmail.es")
        self.combobox_dominios_from.addItem("Hotmail.mx")
        self.combobox_dominios_from.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_to = QComboBox()
        self.combobox_dominios_to.addItem("Gmail.com")
        self.combobox_dominios_to.insertSeparator(1)
        self.combobox_dominios_to.addItem("Outlook.com")
        self.combobox_dominios_to.addItem("Outlook.es")
        self.combobox_dominios_to.insertSeparator(4)
        self.combobox_dominios_to.addItem("Hotmail.com")
        self.combobox_dominios_to.addItem("Hotmail.es")
        self.combobox_dominios_to.addItem("Hotmail.mx")
        self.combobox_dominios_to.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_from.currentTextChanged.connect(
            self.verificar_opcion)
        self.combobox_dominios_to.currentTextChanged.connect(
            self.verificar_opcion)
        self.pushbutton_enviar.clicked.connect(self.presionado)

        self.layout_main = QHBoxLayout(self)

        self.layout_principal = QVBoxLayout()
        self.layout_principal.addWidget(self.label_user_email)
        self.layout_principal.addWidget(self.line_edit_user_email)
        self.layout_principal.addWidget(self.label_user_password)
        self.layout_principal.addWidget(self.line_edit_user_password)
        self.layout_principal.addWidget(self.label_victima_email)
        self.layout_principal.addWidget(self.line_edit_victima_email)
        self.layout_principal.addWidget(self.label_user_asunto)
        self.layout_principal.addWidget(self.line_edit_user_asunto)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_uno)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_varios)
        self.layout_principal.addWidget(self.pushbutton_enviar)
        self.layout_principal.addWidget(self.label_estado_proceso)
        self.layout_principal.addWidget(self.combobox_dominios_from)
        self.layout_principal.addWidget(self.combobox_dominios_to)
        self.layout_principal.addWidget(self.label_proceso)
        self.layout_principal.addWidget(self.label_proceso_verificacion)
        self.layout_principal.addWidget(self.label_proceso2)
        self.layout_principal.addWidget(self.label_proceso_verificacion2)
        self.layout_principal.addWidget(self.label_proceso3)
        self.layout_principal.addWidget(self.label_proceso_verificacion3)

        self.layout_secundario = QVBoxLayout()
        self.textarea_proceso = QTextEdit()
        self.textarea_proceso.setPlaceholderText("ESPERANDO PARA PROCESAR")
        self.textarea_proceso.setFont(QFont("Times", 14, QFont.Bold, True))
        self.textarea_proceso.setGeometry(0, 0, 500, 400)
        self.textarea_proceso.setStyleSheet(
            "color: yellow; background-color:black; border-style:solid")
        self.textarea_proceso.setReadOnly(False)
        self.textarea_proceso.setOverwriteMode(QTextEdit.WidgetWidth)
        self.layout_secundario.addWidget(self.textarea_proceso)

        self.layout_main.addLayout(self.layout_principal, 4)
        self.layout_main.addLayout(self.layout_secundario, 4)
Пример #53
0
 def __init__(self):
     super().__init__()
     uic.loadUi('testing.ui', self)
     oImage = QImage("фон_тест.jpg")
     sImage = oImage.scaled(QSize(1050, 600))
     palette = QPalette()
     palette.setBrush(QPalette.Window, QBrush(sImage))
     self.setPalette(palette)
     self.dct = {
         '00.jpg': '3',
         '01.jpg': '6',
         '02.jpg': '6',
         '03.jpg': '3',
         '04.jpg': '4',
         '05.jpg': '5',
         '06.jpg': '4',
         '07.jpg': '4',
         '08.jpg': '6',
         '09.jpg': '5',
         '10.jpg': '6',
         '11.jpg': '4',
         '12.jpg': '3',
         '13.jpg': '3',
         '14.jpg': '4',
         '15.jpg': '6',
         '16.jpg': '2',
         '17.jpg': '3',
         '18.jpg': '5',
         '19.jpg': '4',
         '20.jpg': '4',
         '21.jpg': '6',
         '22.jpg': '6',
         '23.jpg': '6',
         '24.jpg': '2',
         '25.jpg': '5',
         '26.jpg': '6',
         '27.jpg': '4',
         '28.jpg': '2',
         '29.jpg': '2',
         '30.jpg': '2',
         '31.jpg': '5',
         '32.jpg': '4',
         '33.jpg': '1',
         '34.jpg': '4',
         '35.jpg': '2',
         '36.jpg': '4',
         '37.jpg': '4',
         '38.jpg': '4',
         '39.jpg': '2',
         '40.jpg': '4',
         '41.jpg': '5',
         '42.jpg': '4',
         '43.jpg': '3',
         '44.jpg': '3',
         '45.jpg': '3',
         '46.jpg': '3',
         '47.jpg': '1',
         '48.jpg': '3',
         '49.jpg': '6',
         '50.jpg': '5',
         '51.jpg': '3',
         '52.jpg': '2',
         '53.jpg': '3',
         '54.jpg': '3',
         '55.jpg': '5',
         '56.jpg': '3',
         '57.jpg': '2',
         '58.jpg': '4',
         '59.jpg': '6',
         '60.jpg': '4',
         '61.jpg': '4',
         '62.jpg': '2',
         '63.jpg': '2',
         '64.jpg': '4',
         '65.jpg': '2',
         '66.jpg': '2',
         '67.jpg': '2',
         '68.jpg': '2',
         '69.jpg': '5',
         '70.jpg': '4',
         '71.jpg': '2',
         '72.jpg': '5',
         '73.jpg': '2',
         '74.jpg': '2',
         '75.jpg': '2',
         '76.jpg': '5',
         '77.jpg': '6',
         '78.jpg': '5',
         '79.jpg': '5',
         '80.jpg': '4',
         '81.jpg': '4',
         '82.jpg': '6',
         '83.jpg': '4',
         '84.jpg': '6',
         '85.jpg': '6',
         '86.jpg': '4',
         '87.jpg': '4',
         '88.jpg': '4',
         '89.jpg': '1',
         '90.jpg': '1',
         '91.jpg': '2',
         '92.jpg': '3',
         '93.jpg': '5'
     }
     self.initUI()
Пример #54
0
                self.play_prev()
            elif event.key() == Qt.Key_Escape:
                self.close()
            elif event.key() == Qt.Key_F:
                self.fullscreen()
            elif event.key() == Qt.Key_Right:
                self.media_seek(5000)
            elif event.key() == Qt.Key_Left:
                self.media_seek(-5000)


if __name__ == '__main__':
    app = QApplication([])
    app.setApplicationName("Test Media")
    app.setStyle("Fusion")
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(25, 25, 25))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)
    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Link, QColor(42, 130, 218))
    palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(palette)
    app.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")
Пример #55
0
    def __init__(self):
        super().__init__()

        self.setFixedWidth(570)
        self.setFixedHeight(410)

        self.controlArea.setFixedWidth(560)

        button_box = gui.widgetBox(self.controlArea, "", addSpace=True, orientation="horizontal")

        self.start_button = gui.button(button_box, self, "Send Beam", callback=self.sendSignal)
        self.start_button.setFixedHeight(45)

        button = gui.button(button_box, self, "Reset Accumulation", callback=self.callResetSettings)
        font = QFont(button.font())
        font.setItalic(True)
        button.setFont(font)
        palette = QPalette(button.palette())  # make a copy of the palette
        palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
        button.setPalette(palette)  # assign new palette
        button.setFixedHeight(45)

        left_box_1 = oasysgui.widgetBox(self.controlArea, "Accumulating Loop Management", addSpace=False, orientation="vertical", height=260)

        gui.comboBox(left_box_1, self, "kind_of_accumulation", label="Accumulated Quantity", labelWidth=350,
                     items=["Number of Good Rays ", "Intensity of Good Rays"],
                     callback=self.set_KindOfAccumulation,
                     sendSelectedValue=False, orientation="horizontal")

        self.left_box_1_1 = oasysgui.widgetBox(left_box_1, "", addSpace=False, orientation="vertical", height=35)
        self.left_box_1_2 = oasysgui.widgetBox(left_box_1, "", addSpace=False, orientation="vertical", height=35)

        oasysgui.lineEdit(self.left_box_1_1, self, "number_of_accumulated_rays", "Number of accumulated good rays\n(before sending signal)", labelWidth=350, valueType=float,
                           orientation="horizontal")

        oasysgui.lineEdit(self.left_box_1_2, self, "number_of_accumulated_rays", "Intenisty of accumulated good rays\n(before sending signal)", labelWidth=350, valueType=float,
                           orientation="horizontal")

        self.set_KindOfAccumulation()

        gui.comboBox(left_box_1, self, "keep_go_rays", label="Remove lost rays from beam", labelWidth=350, items=["No", "Yes"], sendSelectedValue=False, orientation="horizontal")

        gui.separator(left_box_1)

        le = oasysgui.lineEdit(left_box_1, self, "current_number_of_rays", "Current number of good rays", labelWidth=350, valueType=int, orientation="horizontal")
        le.setReadOnly(True)
        font = QtGui.QFont(le.font())
        font.setBold(True)
        le.setFont(font)
        palette = QtGui.QPalette(le.palette())  # make a copy of the palette
        palette.setColor(QtGui.QPalette.Text, QtGui.QColor('dark blue'))
        palette.setColor(QtGui.QPalette.Base, QtGui.QColor(243, 240, 160))
        le.setPalette(palette)

        self.le_current_intensity = oasysgui.lineEdit(left_box_1, self, "current_intensity", "Current intensity", labelWidth=350, valueType=float, orientation="horizontal")
        self.le_current_intensity.setReadOnly(True)
        font = QtGui.QFont(self.le_current_intensity.font())
        font.setBold(True)
        self.le_current_intensity.setFont(font)
        palette = QtGui.QPalette(le.palette())  # make a copy of the palette
        palette.setColor(QtGui.QPalette.Text, QtGui.QColor('dark blue'))
        palette.setColor(QtGui.QPalette.Base, QtGui.QColor(243, 240, 160))
        self.le_current_intensity.setPalette(palette)

        le = oasysgui.lineEdit(left_box_1, self, "current_number_of_lost_rays", "Current number of lost rays", labelWidth=350, valueType=int, orientation="horizontal")
        le.setReadOnly(True)
        palette = QtGui.QPalette(le.palette())  # make a copy of the palette
        palette.setColor(QtGui.QPalette.Text, QtGui.QColor('dark red'))
        palette.setColor(QtGui.QPalette.Base, QtGui.QColor(243, 240, 160))
        le.setPalette(palette)

        le = oasysgui.lineEdit(left_box_1, self, "current_number_of_total_rays", "Current number of total rays", labelWidth=350, valueType=int, orientation="horizontal")
        le.setReadOnly(True)
        palette = QtGui.QPalette(le.palette())  # make a copy of the palette
        palette.setColor(QtGui.QPalette.Text, QtGui.QColor('black'))
        palette.setColor(QtGui.QPalette.Base, QtGui.QColor(243, 240, 160))
        le.setPalette(palette)


        gui.rubber(self.controlArea)
def colour(widget, color):
    palette = QPalette()
    palette.setColor(QPalette.Window, color)
    widget.setAutoFillBackground(True)
    widget.setPalette(palette)
Пример #57
0
    def setupUi(self):
        style_sheet = """
            QTableWidget {
                border: none;
                background-color:rgb(255,255,255)
                
            }
            QPushButton{
                
                border-radius:25px;
                background-color:rgb(255, 255, 255); 
                color: rgb(0, 0, 0);
                font-size:15px;
                font-family:华文隶书;
            }
            QPushButton:pressed{
                background-color:rgb(173, 115, 0)
            }
            QLineEdit{
                
                font-size:15px;
                font-family:华文隶书;
            }
            QLabel
            {
                
                font-size:18px;
                font-family:华文隶书;
            }
            
        """
        self.setWindowTitle("History Record")
        self.setMinimumSize(1000, 400)
        self.setMaximumSize(1000, 400)

        # data=test_data.get_test_data(1)
        data_list = data_operation.get_record_list(1, 10)
        data = self.convert_data_to_dict(data_list)
        # self.table = QTableWidget(len(data), 4)  # 3 行 5 列的表格
        self.table = QTableWidget(10, 6)
        palette = QPalette()
        palette.setBrush(QPalette.Background,
                         QBrush(QPixmap('userInterface/haoche.jpg')))
        self.setPalette(palette)
        self.table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)  # 自适应宽度
        # self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自适应宽度
        self.table.setHorizontalHeaderLabels(
            ['date', 'scenario', 'agent name', 'score', 'see details', 'id'])
        font = QtGui.QFont()
        font.setFamily("华文隶书")
        font.setPointSize(10)
        self.table.setFont(font)
        self.__layout = QVBoxLayout()
        self.__layout.addWidget(self.table)
        self.setLayout(self.__layout)
        self.setStyleSheet(style_sheet)
        # self.setPageController(int(len((data))/10+1))  # 表格设置页码控制
        self.setPageController(
            self.get_total_page())  # setting the total page number
        self.control_signal.connect(self.page_controller)
        self.control_signal.connect(self.page_controller)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.queryButton = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        self.table.setColumnHidden(5, True)
        for dataId in range(10):

            self.queryButton[dataId] = QtWidgets.QPushButton('See details')
            self.queryButton[dataId].setDown(False)
        for dataId in range(len(data)):
            self.table.setItem(dataId, 0,
                               QTableWidgetItem(data[dataId]['date']))
            self.table.setItem(dataId, 1,
                               QTableWidgetItem(data[dataId]['scenario']))
            self.table.setItem(dataId, 2,
                               QTableWidgetItem(data[dataId]['agent name']))
            self.table.setItem(dataId, 3,
                               QTableWidgetItem(data[dataId]['score']))
            self.table.setCellWidget(dataId, 4, self.queryButton[dataId])
            self.table.setItem(dataId, 5,
                               QTableWidgetItem(str(data[dataId]['id'])))
Пример #58
0
class ClassificationUI(QWidget):
    def __init__(self):
        super().__init__()

        self.show_log = False

        # create a palette, used to set color
        self.pe = QPalette()
        """ UI for training  """
        choose_train_data = QPushButton('choose train data')
        self.start_train = QPushButton('Start training')
        self.stop_train = QPushButton('Stop training')

        choose_train_data.clicked.connect(self.show_train_dialog)
        self.start_train.clicked.connect(self.start_train_func)
        self.stop_train.clicked.connect(self.stop_train_func)

        # used to show the chosen training directory
        self.train_dir_edit = QLineEdit()

        # used to show training statics
        self.statics_label = QLabel('')
        self.statics_label.setAlignment(Qt.AlignTop)
        self.statics_label.setAutoFillBackground(True)
        self.pe.setColor(QPalette.Background, Qt.white)
        self.statics_label.setPalette(self.pe)

        self.loss_label = QLabel('')
        self.pe.setColor(QPalette.Background, Qt.white)
        self.loss_label.setAutoFillBackground(True)
        self.loss_label.setPalette(self.pe)
        self.resize_image(path="./buffer/blank.jpg", mode='loss')
        loss_im = QPixmap("./buffer/loss_buffer.jpg")
        loss_im = loss_im.scaledToWidth(430)
        loss_im = loss_im.scaledToHeight(300)
        self.loss_label.setPixmap(loss_im)

        # add buttons, label, and edit to the ui
        grid_train = QGridLayout()
        grid_train.setSpacing(10)

        grid_train.addWidget(choose_train_data, 1, 0)
        grid_train.addWidget(self.train_dir_edit, 1, 1, 1, 3)
        grid_train.addWidget(self.start_train, 1, 4, 1, 2)
        grid_train.addWidget(self.stop_train, 1, 6, 1, 2)
        grid_train.addWidget(self.statics_label, 2, 0, -1, 4)
        grid_train.addWidget(self.loss_label, 2, 4, -1, 4)
        """ UI for testing """
        choose_test_data = QPushButton('choose test data')
        choose_test_data.clicked.connect(self.show_test_dialog)

        self.test_dir_edit = QLineEdit()

        # create a label to show image
        self.image_label = QLabel()
        self.resize_image(path="./buffer/blank.jpg", mode='test')
        test_im = QPixmap("./buffer/test_buffer.jpg")
        test_im = test_im.scaledToWidth(430)
        test_im = test_im.scaledToHeight(430)
        self.image_label.setPixmap(test_im)

        self.results_label = QLabel('Results')
        self.results_label.setAlignment(Qt.AlignCenter)
        self.pe.setColor(QPalette.Background, Qt.lightGray)
        self.results_label.setAutoFillBackground(True)
        self.results_label.setPalette(self.pe)

        # add thses buttons, labels, edit to the ui
        grid_test = QGridLayout()
        grid_test.setSpacing(10)

        grid_test.addWidget(choose_test_data, 1, 0)
        grid_test.addWidget(self.test_dir_edit, 1, 1, 1, 3)
        grid_test.addWidget(self.image_label, 2, 0, -1, 4)
        grid_test.addWidget(self.results_label, 1, 4, 1, 4)

        # create ui for test results
        self.pe.setColor(QPalette.Background, Qt.white)

        collar_label = QLabel('领子设计')
        collar_label.setAlignment(Qt.AlignCenter)
        self.collar_result = QLabel('')
        self.collar_result.setAutoFillBackground(True)
        self.collar_result.setPalette(self.pe)
        self.collar_result.setAlignment(Qt.AlignCenter)

        neckline_label = QLabel('颈线设计')

        neckline_label.setAlignment(Qt.AlignCenter)
        self.neckline_result = QLabel('')
        self.neckline_result.setAutoFillBackground(True)
        self.neckline_result.setPalette(self.pe)
        self.neckline_result.setAlignment(Qt.AlignCenter)

        neck_label = QLabel('脖颈设计')
        neck_label.setAlignment(Qt.AlignCenter)
        self.neck_result = QLabel('')
        self.neck_result.setAutoFillBackground(True)
        self.neck_result.setPalette(self.pe)
        self.neck_result.setAlignment(Qt.AlignCenter)

        lapel_label = QLabel('翻领设计')
        lapel_label.setAlignment(Qt.AlignCenter)
        self.lapel_result = QLabel('')
        self.lapel_result.setAutoFillBackground(True)
        self.lapel_result.setPalette(self.pe)
        self.lapel_result.setAlignment(Qt.AlignCenter)

        coat_label = QLabel('衣长')
        coat_label.setAlignment(Qt.AlignCenter)
        self.coat_result = QLabel('')
        self.coat_result.setAutoFillBackground(True)
        self.coat_result.setPalette(self.pe)
        self.coat_result.setAlignment(Qt.AlignCenter)

        pant_laebl = QLabel('裤长')
        pant_laebl.setAlignment(Qt.AlignCenter)
        self.pant_result = QLabel('')
        self.pant_result.setAutoFillBackground(True)
        self.pant_result.setPalette(self.pe)
        self.pant_result.setAlignment(Qt.AlignCenter)

        skirt_label = QLabel('裙长')
        skirt_label.setAlignment(Qt.AlignCenter)
        self.skirt_result = QLabel('')
        self.skirt_result.setAutoFillBackground(True)
        self.skirt_result.setPalette(self.pe)
        self.skirt_result.setAlignment(Qt.AlignCenter)

        sleeve_label = QLabel('袖长')
        sleeve_label.setAlignment(Qt.AlignCenter)
        self.sleeve_result = QLabel('')
        self.sleeve_result.setAutoFillBackground(True)
        self.sleeve_result.setPalette(self.pe)
        self.sleeve_result.setAlignment(Qt.AlignCenter)

        grid_test.addWidget(collar_label, 2, 4, 1, 2)
        grid_test.addWidget(self.collar_result, 3, 4, 1, 2)
        grid_test.addWidget(neckline_label, 2, 6, 1, 2)
        grid_test.addWidget(self.neckline_result, 3, 6, 1, 2)
        grid_test.addWidget(neck_label, 4, 4, 1, 2)
        grid_test.addWidget(self.neck_result, 5, 4, 1, 2)
        grid_test.addWidget(lapel_label, 4, 6, 1, 2)
        grid_test.addWidget(self.lapel_result, 5, 6, 1, 2)
        grid_test.addWidget(coat_label, 6, 4, 1, 2)
        grid_test.addWidget(self.coat_result, 7, 4, 1, 2)
        grid_test.addWidget(pant_laebl, 6, 6, 1, 2)
        grid_test.addWidget(self.pant_result, 7, 6, 1, 2)
        grid_test.addWidget(skirt_label, 8, 4, 1, 2)
        grid_test.addWidget(self.skirt_result, 9, 4, 1, 2)
        grid_test.addWidget(sleeve_label, 8, 6, 1, 2)
        grid_test.addWidget(self.sleeve_result, 9, 6, 1, 2)
        """ combine two grid """
        upper_grid = QGridLayout()
        upper_grid.setSpacing(10)

        upper_grid.addLayout(grid_train, 1, 0)
        upper_grid.addLayout(grid_test, 2, 0)
        """ show the ui """
        self.setLayout(upper_grid)
        self.setGeometry(300, 100, 890, 860)
        self.setWindowTitle('image classification')
        self.setFixedSize(890, 860)
        self.show()

    def show_test_dialog(self):
        fname = QFileDialog.getOpenFileName(
            self, 'Open file', '/data0/yangwf/FashionAI/base/Images')[0]
        self.test_dir_edit.setText(fname)

        self.while_testing()

        self.test_thread = threading.Thread(target=self.make_prediction,
                                            name='test_thread')
        self.test_thread.start()

    def fill_log(self):
        while True:
            if not self.show_log:
                break
            time.sleep(1)  # flash every 0.5 seconds
            if not os.path.exists('./buffer/loss.jpg'):
                continue
            else:

                self.resize_image(path='./buffer/loss.jpg', mode='loss')
                loss_im = QPixmap("./buffer/loss_buffer.jpg")
                loss_im = loss_im.scaledToWidth(430)
                loss_im = loss_im.scaledToHeight(300)
                self.loss_label.setPixmap(loss_im)
                # print('exist loss buffer jpg')

            if not os.path.exists("./buffer/log.log"):
                continue
            else:
                content = open("./buffer/log.log").readlines()
                if len(content) > 11:
                    content = content[-11:]
                content = "\n".join(content)
                self.statics_label.setText(content)

    def show_train_dialog(self):
        fname = QFileDialog.getExistingDirectory(self, 'Open file',
                                                 '/data0/yangwf/')
        self.train_dir_edit.setText(fname)
        return

    def start_train_func(self):

        # add the train data path
        fname = self.train_dir_edit.text()
        train_data_root_path = './buffer/train_data_root.txt'
        train_file = open(train_data_root_path, mode='a')
        train_file.write('\n' + fname)
        train_file.close()
        # initialize the loss figure
        self.resize_image(path="./buffer/blank.jpg", mode='loss')
        loss_im = QPixmap("./buffer/loss_buffer.jpg")
        loss_im = loss_im.scaledToWidth(430)
        loss_im = loss_im.scaledToHeight(300)
        self.loss_label.setPixmap(loss_im)
        """ begin to train the cnn model """
        self.statics_label.setText(
            'begin to train, launching..., please waite...')
        self.train_sp = subprocess.Popen('bash ./buffer/train_cnn_model.sh',
                                         shell=True)
        pid = self.train_sp.pid
        print('Train cnn model pid: ', pid)

        self.show_log = True

        self.show_log_thread = threading.Thread(target=self.fill_log,
                                                name="fill_log_thread")
        self.show_log_thread.start()

    def stop_train_func(self):
        self.show_log = False
        os.remove('./buffer/log.log')
        os.remove('./buffer/train_data_root.txt')
        os.remove('./buffer/loss.jpg')
        os.remove('./buffer/loss_buffer.jpg')

        # pid = self.train_thread.pid
        # print(pid)
        os.kill(
            self.train_sp.pid + 3, signal.SIGTERM
        )  # self.train_thread.pid + 3, because we don't know why the pid should pluse 3

    def resize_image(self, path, mode):
        img = Image.open(path)
        if mode == 'test':
            img = img.resize((430, 430))
            img.save("./buffer/test_buffer.jpg")
        elif mode == 'loss':
            img = img.resize((430, 300))
            img.save("./buffer/loss_buffer.jpg")

    def make_prediction(self):
        im_path = self.test_dir_edit.text()
        labels = {
            'neckline_design_labels': [
                '不存在', 'V领', '圆领', '深V领', '方领', '不规则领', '抹胸领', '一字领', '露肩领',
                '半开领', '桃形领'
            ],
            'collar_design_labels': ['不存在', '娃娃领', '清道夫领', '衬衫领', '飞行员领'],
            'neck_design_labels': ['不存在', '荷叶半高领', '常规半高领', '堆堆领', '高常规领'],
            'lapel_design_labels': ['不存在', '西装领', '一片领', '青果领', '直线领'],
            'sleeve_length_labels':
            ['不存在', '无袖', '杯袖', '短袖', '五分袖', '七分袖', '九分袖', '长袖', '超长袖'],
            'coat_length_labels':
            ['不存在', '高腰', '正常', '长款', '加长款', '及膝', '超长', '及地'],
            'skirt_length_labels': ['不存在', '短袖', '中裙', '七分裙', '九分群', '长裙'],
            'pant_length_labels': ['不存在', '短裤', '五分裤', '七分裤', '九分裤', '长裤']
        }

        tasks_all = [
            'collar_design_labels', 'neckline_design_labels',
            'skirt_length_labels', 'sleeve_length_labels',
            'neck_design_labels', 'coat_length_labels', 'lapel_design_labels',
            'pant_length_labels'
        ]

        results = inference(im_path)

        for idx, key, in enumerate(tasks_all):
            a_predition = results[key]
            a_predition = labels[key][int(
                a_predition[0])] + '\n' + 'p = ' + str(a_predition[1])

            if key == tasks_all[0]:
                self.collar_result.setText(a_predition)
            elif key == tasks_all[1]:
                self.neckline_result.setText(a_predition)
            elif key == tasks_all[2]:
                self.skirt_result.setText(a_predition)
            elif key == tasks_all[3]:
                self.sleeve_result.setText(a_predition)
            elif key == tasks_all[4]:
                self.neck_result.setText(a_predition)
            elif key == tasks_all[5]:
                self.coat_result.setText(a_predition)
            elif key == tasks_all[6]:
                self.lapel_result.setText(a_predition)
            elif key == tasks_all[7]:
                self.pant_result.setText(a_predition)

        self.pe.setColor(QPalette.Background, Qt.lightGray)
        self.results_label.setPalette(self.pe)
        self.results_label.setText('Results')

    def while_testing(self):
        fname = self.test_dir_edit.text()
        # show test image
        self.resize_image(path=fname, mode='test')
        test_im = QPixmap("./buffer/test_buffer.jpg")
        test_im = test_im.scaledToWidth(430)
        test_im = test_im.scaledToHeight(430)
        self.image_label.setPixmap(test_im)

        # show other nformation
        self.pe.setColor(QPalette.Background, Qt.green)
        self.results_label.setPalette(self.pe)
        self.results_label.setText('testing... please waite')

        self.collar_result.setText('')
        self.neckline_result.setText('')
        self.skirt_result.setText('')
        self.sleeve_result.setText('')
        self.neck_result.setText('')
        self.coat_result.setText('')
        self.lapel_result.setText('')
        self.pant_result.setText('')
Пример #59
0
class main_principal(QWidget):
    fecha_actual = datetime.datetime.now(
    )  # datetime es la libreria que nos ayuda con las fechas horas minutos y hsta segundos
    #en este caso nos referimos a que nos de la fecha actual
    contador_hilo = 1
    cursor = None
    lista_hilos = []

    def banner_anonymous(self):
        #banner un bannner es solo un mensaje de texto
        #el       \32 es para indicarle que queremos un espacio en blanco
        #puedes ver que hay muchos \32 en este paratado eso es debido a que
        #se necesitan espacios para imprimir bien el banner
        self.textarea_proceso.append(
            "$$$$$\32$\32\32\32\32$\32\32$$$$$\32$\32\32\32\32\32$$$$$$$\32\32\32\32\32\32######\32#####\32######\32##\32\32\32##"
        )
        self.textarea_proceso.append(
            "$\32\32\32\32\32\32\32\32$\32\32\32\32$\32\32\32\32\32$\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32\32#\32\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$$$$$\32\32\32$\32\32\32\32\32$$$$$\32$\32\32\32\32\32$\32\32\32\32\32$||||||\32\32\32\32\32######\32#####\32######\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$\32\32\32\32\32\32$\32\32$\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32\32$\32\32\32\32\32\32\32\32\32\32\32#|#\32\32\32\32\32#\32\32\32\32#\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$$$$$\32$\32\32\32\32$\32\32$\32\32\32\32\32$$$$$\32$$$$$$$\32\32\32\32\32\32######\32#\32\32\32\32\32#\32\32\32\32#\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "Autor: Aldair Martinez Alias Hans Krammler Junior"
        )  # Aqui declaramos mi nombre jajaj XD

    def spam_uno_a_uno(self):
        self.banner_anonymous()
        print(self.fecha_actual)

    def spam_uno_a_varios(self):
        self.banner_anonymous()
        print(self.fecha_actual)
        print(Fore.GREEN + "HAZ ELEGIDO ENVIAR DESDE TU COREO A OTROS CORREO")

    def mensaje(self):
        print("SE TERMINO EL HILO")

    contador_hilo_aux = 0
    lista_hilos = []
    workers = []
    threads = []

    def incializa_hilos(self):
        if self.contador_hilo == 1:
            self.thread = QThread()
            self.thread.setObjectName("Hilo_1")
            self.worker = Worker(self.contador_hilo, self.textarea_proceso,
                                 self.label_proceso_verificacion, None)
            self.worker.moveToThread(self.thread)
            self.thread.setTerminationEnabled(True)
            self.thread.started.connect(self.worker.run)
            self.worker.finished.connect(self.terminado)
            self.thread.finished.connect(
                lambda: self.verificar_resultado_hilo(self.thread))
            self.worker.progressed.connect(
                lambda: self.reportProgress(self.worker))
            self.worker.siguiente.connect(
                lambda: self.siguiente_hilo(self.thread))
            self.thread.finished.connect(self.thread.quit)
            self.lista_hilos.append(self.thread)
            return self.lista_hilos
        else:
            self.lista_hilos = []
            self.threads.append(QThread())
            self.threads[self.contador_hilo_aux].setObjectName("Hilo_2")
            if self.contador_hilo == 2:
                print("Aqui tambien funciona")
                self.workers.append(
                    Worker(self.contador_hilo, self.textarea_proceso, None,
                           self.label_proceso_verificacion2))
            elif self.contador_hilo == 3:
                self.workers.append(
                    Worker(self.contador_hilo, self.textarea_proceso, None,
                           self.label_proceso_verificacion3))
            self.workers[self.contador_hilo_aux].moveToThread(
                self.threads[self.contador_hilo_aux])
            self.threads[self.contador_hilo_aux].started.connect(
                self.workers[self.contador_hilo_aux].run)
            self.workers[self.contador_hilo_aux].finished.connect(
                self.terminado)
            print("Pasando terminado")
            self.threads[self.contador_hilo_aux].finished.connect(
                lambda: self.verificar_resultado_hilo(self.threads[
                    self.contador_hilo_aux]))
            print("Pasando verificar resultado")
            self.workers[self.contador_hilo_aux].progressed.connect(
                lambda: self.reportProgress(self.workers[self.contador_hilo_aux
                                                         ]))
            print("Pasando reportprogress")
            self.workers[self.contador_hilo_aux].siguiente.connect(
                lambda: self.siguiente_hilo(self.threads[self.contador_hilo_aux
                                                         ]))
            self.threads[self.contador_hilo_aux].finished.connect(
                self.threads[self.contador_hilo_aux].quit)
            print("Pasando quit")
            self.lista_hilos.append(self.threads[self.contador_hilo_aux])
            return self.lista_hilos
        return None

    def siguiente_hilo(self, hilo):
        if self.contador_hilo == 1:
            if hilo.isRunning() == False:
                if hilo.isFinished() == True:
                    print("si funciono")
                    hilo.finished.connect(hilo.deleteLater)
                    hilo.finished.connect(hilo.terminate)
                    self.contador_hilo = self.contador_hilo + 1
                    self.incializa_hilos()[0].start()
        elif self.contador_hilo > 1:
            if self.get_verificado() == -1:
                return -1
            elif self.get_verificado() == -2:
                return -2
            else:
                return -3
            if hilo.isRunning() == False:
                if hilo.isFinished() == True:
                    self.contador_hilo = self.contador_hilo + 1
                    self.contador_hilo_aux = self.contador_hilo_aux + 1
                    self.incializa_hilos()[0].start()

        return 0

    cursor = None
    estado_hilo_x = 0
    lista_verificado = []

    def set_verificado(self, estado):
        self.estado_hilo_x = estado

    def get_verificado(self):
        self.lista_verificado.append(self.estado_hilo_x)
        print("get.lista.verificado" + str(self.lista_verificado[0]))
        return int(self.lista_verificado[0])

    def terminado(self):
        if self.contador_hilo == 1:
            print("TRABAJO TERMINADO")
            self.thread.finished.emit()
        elif self.contador_hilo > 1:
            self.threads[self.contador_hilo_aux].finished.emit()

    def verificar_resultado_hilo(self, thread):
        if self.contador_hilo == 1:
            if self.thread.isRunning() == False:
                print("EL HILO 1 HA TERMINADO SU TAREA")
            if self.thread.isFinished() == True:
                print("EL HILI 1 TERMINO CON EXITO")
                self.worker.progressed.emit()
        elif self.contador_hilo > 1:
            print(str(self.contador_hilo_aux))
            if thread.isRunning() == False:
                print("EL HILO" + str(self.contador_hilo_aux) +
                      "ESTA CORRIENDO")
            if thread.isFinished() == True:
                print("EL HILO" + str(self.contador_hilo_aux) + "HA TERMINADO")
                self.workers[self.contador_hilo_aux].progressed.emit()

    porcentaje = 10
    _i = 0
    lista_progreso = ["INICIANDO HILO DE EJECUCION......"]

    def reportProgress(self, worker):
        print(self.contador_hilo)
        if self.contador_hilo == 1:
            print("REPORTANDO HILO")
            #print("POSICION ACTUAL DEL CURSOR"+str(int(self.textarea_proceso.textCursor().position())))
            worker.siguiente.emit()
        else:
            if self.contador_hilo == 2:
                email = self.line_edit_user_email.text()
                password = self.line_edit_user_password.text()
                longitud_email = len(email)
                longitud_password = len(password)
                if longitud_email == 0 or longitud_password == 0:

                    self.set_verificado(-1)
            elif self.contador_hilo == 3:
                email = self.line_edit_user_email.text()
                email_to_list = list(email)
                contador = 1
                for _x in len(email):
                    if email_to_list[_x] == "@":
                        contador = contador + 1
                if contador > 1:
                    self.set_verificado(-2)
            elif self.contador_hilo == 4:
                contador = 1
                email_dominio = email.split(".")
                textarea_proceso.append("DIVIDIENDO TU EMAIL--->" +
                                        email_dominio)
                longitud_dominio_email = len(email_dominio)
                textarea_proceso.append(
                    "VERIFICANDO COINCIDENCIA DE DOMINIO DE EMAIL....")
                dominios = [
                    "gmail.com", "outlook.com", "outlook.es", "hotmail.com",
                    "hotmail.mx", "hotmail.es"
                ]
                longitud_dominio_gmail = len(dominios[0])
                longitud_dominio_outlook_com = len(dominios[1])
                longitud_dominio_outlook_es = len(dominios[2])
                longitud_dominio_hotmail_com = len(dominios[3])
                longitud_dominio_hotmail_mx = len(dominios[4])
                longitud_dominio_hotmail_es = len(dominios[5])
                for _i in range(longitud_dominio_email):
                    for _j in (range(longitud_dominio_gmail)
                               or range(longitud_dominio_outlook_com)
                               or range(longitud_dominio_outlook_es)
                               or range(longitud_dominio_hotmail_com)
                               or range(longitud_dominio_hotmail_mx)
                               or range(longitud_dominio_hotmail_es)):
                        if _j < longitud_dominio_gmail:
                            if dominios[0][_j] == email_dominio[1][_j]:
                                print(dominios[0][j])
                                contador = contador + 1
                        elif _j < longitud_dominio_outlook_com:
                            if dominios[1][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_outlook_es:
                            if dominios[2][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_com:
                            if dominios[3][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_mx:
                            if dominios[4][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_es:
                            if dominios[5][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                    if contador > longitud_dominio_gmail:
                        return -3
                    else:
                        contador = 1
            print("AQUI MEN")
            posicion_textarea = len(self.lista_progreso[self._i])
            self.cursor = self.textarea_proceso.textCursor()
            print("CURSOR ACTUAL" + str(self.cursor))
            print("POSICION CURSOR ACTUAL++" + str(self.cursor.position()))
            if self.cursor.atEnd() == True:
                print("FIN DEL CURSOR True")
                print("TEXTO SELECCIONADO ANTES" + self.cursor.selectedText())
                posicion_inicial = (self.cursor.position() -
                                    1) - (posicion_textarea - 1) + 1
                print("posicion inicial" + str(posicion_inicial))
                time.sleep(0.4)
                self.cursor.setPosition(posicion_inicial,
                                        QTextCursor.KeepAnchor)
                print("TEXTO SELECCIONADO AHORA" + self.cursor.selectedText())
                print("POSICION CURSOR ACTUAL--" + str(self.cursor.position()))
                self.progreso = self.cursor.selectedText() + str(
                    self.porcentaje)
                self.porcentaje = self.porcentaje + 10
                self.textarea_proceso.append(self.progreso)
                print("POSICION CURSOR ACTUAL++" + str(self.cursor.position()))
            self._i = self._i + 1
            worker.siguiente.emit()

    def verificar_opcion(self):
        pass

    def validar_oprciones(self):
        if self.checkbox_opcion_spam_uno_a_uno.isChecked(
        ) == True and self.checkbox_opcion_spam_uno_a_varios.isChecked():
            self.label_estado_proceso.setText(
                Fore.RED +
                "LO SIENTO NO PUEDES SELECCIONAR DOS OPCIONES A LA VEZ")
            return False
        else:
            return True

    def escannear_red(self):
        scan = nmap.PortScanner()
        informacion_sistema = os.uname()

    def presionado(self):
        resultado_validar_opciones = self.validar_oprciones()
        if resultado_validar_opciones == True:
            self.inciar_hilo_principal()
            self.resultado_verificacion_email = 0
            if self.resultado_verificacion_email == 0:
                print("PASANDO AL SIGUIENTE HILO DE EJECUCION")
            if self.resultado_verificacion_email == 1:
                if self.checkbox_opcion_spam_uno_a_uno.isChecked() == True:
                    print(
                        "LAS OCPIONES SELECCIONADAAS EN LOS CASILLA SON VALIDAS"
                    )
            else:
                if self.resultado_verificacion_email == -1 or self.resultado_verificacion_email == -2 or self.resultado_verificacion_email == -3:
                    if self.resultado_verificacion_email == -1:
                        self.label_estado_proceso.setText(
                            "NO HAS INGRESADO NADA EN EL PRIMER CAMPO")
                        self.textarea_proceso.append(
                            "ERROR NO HAS INGRESADO NADA EN EL PRIMER CAMPO")
                    elif self.resultado_verificacion_email == -2:
                        self.label_estado_proceso.setText(
                            "HAS MAS DE UN ARROBA EN TU CORREO")
                        self.textarea_proceso.append(
                            "ERROR HAY MAS DE UN ARROBA EN TU CORREO")
                    elif self.resultado_verificacion_email == -3:
                        self.label_estado_proceso.setText(
                            "TERMINACION DE CORREO NO VALIDA")

        else:
            self.textarea_proceso.append(
                "INTENTE DE NUEVO RELLENAR LOS CAMPOS ADECUADAMENTE")

    def __init__(self, parent=None):
        #Parte de intefaz grafica
        super().__init__(parent)

        self.color = QColor(0, 0, 0, 0.5)
        self.setGeometry(550, 100, 1500, 500)
        self.pallette = QPalette(self.color)
        self.pallette.setColor(QPalette.Text, Qt.cyan)

        self.titulo_ventana = "ENVIO DE CORREO PARA HACER SPAM"
        self.setWindowTitle(self.titulo_ventana)
        self.setStyleSheet(
            "border-color: cyan; border-style: dashed; border-width: 2px; color:white"
        )
        self.setPalette(self.pallette)
        self.checkbox_opcion_spam_uno_a_uno = QCheckBox(
            "REALIZAR SPAM UNO A UN CORREO")
        self.checkbox_opcion_spam_uno_a_uno.clicked.connect(
            self.spam_uno_a_uno)
        self.checkbox_opcion_spam_uno_a_varios = QCheckBox(
            "REALIZAR SPAM UNO A VARIOS COOREOS")
        self.checkbox_opcion_spam_uno_a_varios.clicked.connect(
            self.spam_uno_a_varios)

        self.label_user_email = QLabel("Ingresa tu direccion de correo: ")
        self.label_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_email.setStyleSheet("color: white")

        self.line_edit_user_email = QLineEdit(self)
        self.line_edit_user_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_email.setStyleSheet("color : black")

        self.label_user_password = QLabel("Ingresa tu password de correo")
        self.label_user_password.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_password.setStyleSheet("color: white")

        self.line_edit_user_password = QLineEdit(self)
        self.line_edit_user_password.setPlaceholderText(
            "Ingresa tu password de tu correo:")
        self.line_edit_user_password.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_password.setStyleSheet("color : black")

        self.label_victima_email = QLabel(
            "Ingresa direccion de correo destinatario: ")
        self.label_victima_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_victima_email.setStyleSheet("color: white")

        self.line_edit_victima_email = QLineEdit(self)
        self.line_edit_victima_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_victima_email.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_victima_email.setStyleSheet("color : black")

        self.label_user_asunto = QLabel("Ingresa el asunto ")
        self.label_user_asunto.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_asunto.setStyleSheet("color: white")

        self.line_edit_user_asunto = QLineEdit(self)
        self.line_edit_user_asunto.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_asunto.setFont(QFont("Times", 14, QFont.Bold,
                                                 True))
        self.line_edit_user_asunto.setStyleSheet("color : black")

        self.pushbutton_enviar = QPushButton("ENVIAR SPAM")
        self.pushbutton_enviar.setFont(QFont("Times", 14, QFont.Bold, True))
        self.pushbutton_enviar.setPalette(self.pallette)

        self.label_estado_proceso = QLabel("")
        self.label_estado_proceso.setText("ESPERANDO DATOS....")

        self.label_proceso = QLabel("Estado verificacion email y password")
        self.label_proceso_verificacion = QLabel("")
        self.label_proceso2 = QLabel(
            "Estado verificacion arroba de email origen y destino")
        self.label_proceso_verificacion2 = QLabel("")
        self.label_proceso3 = QLabel(
            "Estado verificacion terminacion correo origen y destino")
        self.label_proceso_verificacion3 = QLabel("")
        self.combobox_dominios_from = QComboBox()
        self.combobox_dominios_from.addItem("Gmail.com")
        self.combobox_dominios_from.insertSeparator(1)
        self.combobox_dominios_from.addItem("Outlook.com")
        self.combobox_dominios_from.addItem("Outlook.es")
        self.combobox_dominios_from.insertSeparator(4)
        self.combobox_dominios_from.addItem("Hotmail.com")
        self.combobox_dominios_from.addItem("Hotmail.es")
        self.combobox_dominios_from.addItem("Hotmail.mx")
        self.combobox_dominios_from.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_to = QComboBox()
        self.combobox_dominios_to.addItem("Gmail.com")
        self.combobox_dominios_to.insertSeparator(1)
        self.combobox_dominios_to.addItem("Outlook.com")
        self.combobox_dominios_to.addItem("Outlook.es")
        self.combobox_dominios_to.insertSeparator(4)
        self.combobox_dominios_to.addItem("Hotmail.com")
        self.combobox_dominios_to.addItem("Hotmail.es")
        self.combobox_dominios_to.addItem("Hotmail.mx")
        self.combobox_dominios_to.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_from.currentTextChanged.connect(
            self.verificar_opcion)
        self.combobox_dominios_to.currentTextChanged.connect(
            self.verificar_opcion)
        self.pushbutton_enviar.clicked.connect(self.presionado)

        self.layout_main = QHBoxLayout(self)

        self.layout_principal = QVBoxLayout()
        self.layout_principal.addWidget(self.label_user_email)
        self.layout_principal.addWidget(self.line_edit_user_email)
        self.layout_principal.addWidget(self.label_user_password)
        self.layout_principal.addWidget(self.line_edit_user_password)
        self.layout_principal.addWidget(self.label_victima_email)
        self.layout_principal.addWidget(self.line_edit_victima_email)
        self.layout_principal.addWidget(self.label_user_asunto)
        self.layout_principal.addWidget(self.line_edit_user_asunto)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_uno)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_varios)
        self.layout_principal.addWidget(self.pushbutton_enviar)
        self.layout_principal.addWidget(self.label_estado_proceso)
        self.layout_principal.addWidget(self.combobox_dominios_from)
        self.layout_principal.addWidget(self.combobox_dominios_to)
        self.layout_principal.addWidget(self.label_proceso)
        self.layout_principal.addWidget(self.label_proceso_verificacion)
        self.layout_principal.addWidget(self.label_proceso2)
        self.layout_principal.addWidget(self.label_proceso_verificacion2)
        self.layout_principal.addWidget(self.label_proceso3)
        self.layout_principal.addWidget(self.label_proceso_verificacion3)

        self.layout_secundario = QVBoxLayout()
        self.textarea_proceso = QTextEdit()
        self.textarea_proceso.setPlaceholderText("ESPERANDO PARA PROCESAR")
        self.textarea_proceso.setFont(QFont("Times", 14, QFont.Bold, True))
        self.textarea_proceso.setGeometry(0, 0, 500, 400)
        self.textarea_proceso.setStyleSheet(
            "color: yellow; background-color:black; border-style:solid")
        self.textarea_proceso.setReadOnly(False)
        self.textarea_proceso.setOverwriteMode(QTextEdit.WidgetWidth)
        self.layout_secundario.addWidget(self.textarea_proceso)

        self.layout_main.addLayout(self.layout_principal, 4)
        self.layout_main.addLayout(self.layout_secundario, 4)

    def inciar_hilo_principal(self):
        self.incializa_hilos()[0].start()
        return 0
Пример #60
0
    def initUi(self):
        # 创建固定窗口大小
        self.setFixedSize(1024, 720)
        # 窗口标题
        self.setWindowTitle('货运信息公共平台')
        # 无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon(':/logo.png'))

        window_pale = QPalette()  # 创建窗口背景图片对象
        window_pale.setBrush(self.backgroundRole(),\
                QBrush(QPixmap("UI/image/mainui.jpg")))        # 按指定路径找到图片
        self.setPalette(window_pale)

        #设置字体颜色
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.white)
        pee = QPalette()
        pee.setColor(QPalette.WindowText, Qt.white)

        # 程序名
        self.lbl_main = QLabel('货运信息公共平台', self)
        self.lbl_main.move(10, 10)
        self.lbl_main.setPalette(pee)

        self.color = "QPushButton{border-image: url(%s);border:none;}"\
                 "QPushButton:hover{border-image: url(%s);border:none;}"

        # 最小化按钮
        self.button_min = QPushButton(' ', self)
        self.button_min.setGeometry(940, 2, 43, 26)
        self.button_min.setFlat(True)
        self.button_min.setToolTip('最小化')
        self.button_min.setStyleSheet(self.color % \
                ('UI/image/mainmin1.png','UI/image/mainmin2.png'))

        # 关闭按钮
        self.button_close = QPushButton(' ', self)
        self.button_close.setGeometry(976, 2, 43, 26)
        self.button_close.setFlat(True)
        self.button_close.setToolTip('关闭')
        self.button_close.setStyleSheet(self.color % \
                ('UI/image/mainclose1.png','UI/image/mainclose2.png'))

        color2 = "QPushButton{border:none;color:rgb(55, 255, 255);}"\
                "QPushButton:hover{border-image: url(%s);border\
                :none;color:rgb(255, 255, 255);}"

        color3 = "QPushButton{border:none;color:rgb(255, 255, 255);}"\
                "QPushButton:hover{border-image: url(%s);border\
                :none;color:rgb(55, 255, 255);}"

        # 先判别一下昵称的长度
        button_user_lang = len(self.user) * 10 + 60

        # 显示登陆的账号 点击退出
        self.button_user = QPushButton('【%s】登陆中' % self.user, self)
        self.button_user.setGeometry(20, 40, button_user_lang, 35)
        self.button_user.setToolTip('点击退出此账号')
        self.button_user.setStyleSheet(color2 % '')

        # 发布信息按钮
        self.button_newmessage = QPushButton('发布信息', self)
        self.button_newmessage.setGeometry(670, 40, 60, 35)
        self.button_newmessage.setStyleSheet(color3 % 'UI/image/focus.png')

        # 我的发布按钮
        self.button_mymessage = QPushButton('我的发布', self)
        self.button_mymessage.setGeometry(750, 40, 60, 35)
        self.button_mymessage.setStyleSheet(color3 % 'UI/image/focus.png')

        color4 = "QPushButton{border:none;color:rgb(55, 255, 255);}"\
                "QPushButton:hover{border:none;color:rgb(55, 255, 255);}"

        # 历史记录按钮
        self.button_record = QPushButton('浏览记录', self)
        self.button_record.setGeometry(830, 40, 60, 35)
        self.button_record.setStyleSheet(color4)

        # 个人资料按钮
        self.button_data = QPushButton('个人资料', self)
        self.button_data.setGeometry(910, 40, 60, 35)
        self.button_data.setStyleSheet(color3 % 'UI/image/focus.png')

        # 创建发货地级联布局
        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(70, 160, 240, 40)
        layout = QHBoxLayout(self.centralwidget)
        self.province_box = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box.setMaxVisibleItems(35)
        self.city_box = QComboBox(self, minimumWidth=73)  # 市
        self.city_box.setMaxVisibleItems(35)
        layout.addWidget(self.province_box)
        province = QLabel("省", self)
        province.setPalette(pe)
        layout.addWidget(province)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout.addWidget(self.city_box)
        city = QLabel("市", self)
        city.setPalette(pe)
        layout.addWidget(city)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))

        # 创建目的地级联布局
        self.centralwidget2 = QWidget(self)
        self.centralwidget2.setGeometry(307, 160, 240, 40)
        layout2 = QHBoxLayout(self.centralwidget2)
        self.province_box2 = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box2.setMaxVisibleItems(35)
        self.city_box2 = QComboBox(self, minimumWidth=73)  # 市
        self.city_box2.setMaxVisibleItems(35)
        layout2.addWidget(self.province_box2)
        province2 = QLabel("省", self)
        province2.setPalette(pe)
        layout2.addWidget(province2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout2.addWidget(self.city_box2)
        city2 = QLabel("市", self)
        city2.setPalette(pe)
        layout2.addWidget(city2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        self.initModel()
        self.initSignal()
        self.initData()

        # 查找按钮
        self.button_find = QPushButton(' ', self)
        self.button_find.setGeometry(534, 93, 104, 129)
        self.button_find.setFlat(True)
        self.button_find.setStyleSheet(self.color % \
                                ('','UI/image/mainfind2.png'))

        color5 = "QPushButton{border:none;color:rgb(0, 0, 0);}"\
                "QPushButton:hover{border-image: url(%s);border\
                :none;color:rgb(255, 255, 255);}"

        # 首页按钮
        self.button_homepage = QPushButton('首页', self)
        self.button_homepage.setGeometry(250, 670, 50, 35)
        self.button_homepage.setFlat(True)
        self.button_homepage.setStyleSheet(color5 % 'UI/image/focus.png')

        # 上一页按钮
        self.button_previouspage = QPushButton('上一页', self)
        self.button_previouspage.setGeometry(310, 670, 50, 35)
        self.button_previouspage.setFlat(True)
        self.button_previouspage.setStyleSheet(color5 % 'UI/image/focus.png')

        # 下一页按钮
        self.button_nextpage = QPushButton('下一页', self)
        self.button_nextpage.setGeometry(370, 670, 50, 35)
        self.button_nextpage.setFlat(True)
        self.button_nextpage.setStyleSheet(color5 % 'UI/image/focus.png')

        self.versions = QLabel('版本号 v18.10', self)
        self.versions.move(900, 685)

        # 创建展示信息目录布局
        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(77, 253, 550, 410)
        self.gridLayout = QGridLayout(self.centralwidget)

        # 第几页面显示
        self.centralwidget2 = QWidget(self)
        self.centralwidget2.setGeometry(60, 670, 100, 35)
        self.gridLayout2 = QGridLayout(self.centralwidget2)

        # 创建历史记录按钮布局
        self.centralwidget_record = QWidget(self)
        self.centralwidget_record.setGeometry(679, 95, 300, 130)
        self.gridLayout_record = QGridLayout(self.centralwidget_record)

        # # 创建详细信息布局
        self.cenparticulars = QWidget(self)
        self.cenparticulars.setGeometry(679, 260, 300, 350)
        self.cenparticulars_1 = QWidget(self)
        self.cenparticulars_1.setGeometry(685, 260, 250, 40)
        self.gridLayout_particulars_1 = QGridLayout(self.cenparticulars_1)
        self.cenparticulars_2 = QWidget(self)
        self.cenparticulars_2.setGeometry(685, 300, 100, 170)
        self.gridLayout_particulars_2 = QGridLayout(self.cenparticulars_2)
        self.cenparticulars_3 = QWidget(self)
        self.cenparticulars_3.setGeometry(755, 300, 100, 151)
        self.gridLayout_particulars_3 = QGridLayout(self.cenparticulars_3)
        self.cenparticulars_4 = QWidget(self)
        self.cenparticulars_4.setGeometry(753, 435, 215, 185)
        self.gridLayout_particulars_4 = QGridLayout(self.cenparticulars_4)
        self.cenparticulars_5 = QWidget(self)
        self.cenparticulars_5.setGeometry(685, 615, 250, 40)
        self.gridLayout_particulars_5 = QGridLayout(self.cenparticulars_5)

        # 定义按键信号和事件绑定
        self.button_min.clicked.connect(self.showMinimized)
        self.button_close.clicked.connect(self.close)

        self.button_user.clicked.connect(self.onuser)
        self.button_find.clicked.connect(self.onfind)
        self.button_homepage.clicked.connect(self.handle_button_homepage)
        self.button_previouspage.clicked.connect(
            self.handle_button_previouspage)
        self.button_nextpage.clicked.connect(self.handle_button_nextpage)