def __init__(self, title=None):
		super(TitleWidget, self).__init__()

		if sys.platform.startswith("darwin"):
			color1 = QColor(230, 230, 230, 255)
			color2 = QColor(177, 177, 177, 255)

			gradient = QLinearGradient()
			gradient.setStart(0, 0)
			gradient.setFinalStop(0, TitleWidget.TitleHeight)
			gradient.setColorAt(0, color1)
			gradient.setColorAt(1, color2)

			brush = QBrush(gradient)
			palette = QPalette()
			palette.setBrush(QPalette.Background, brush)
			self.setPalette(palette)
			self.setAutoFillBackground(True)

		self.setMaximumHeight(TitleWidget.TitleHeight)
		self.setMinimumHeight(TitleWidget.TitleHeight)

		self.titleLabel = QLabel("", parent=self)
		font = self.titleLabel.font()
		font.setPixelSize(11)
		self.titleLabel.setFont(font)
		self.titleLabel.setAlignment(Qt.AlignCenter)
		self.titleLabel.setText(title)

		layout = QVBoxLayout()
		layout.setSpacing(0)
		layout.setContentsMargins(0, 0, 0, 0)
		layout.addWidget(self.titleLabel)
		self.setLayout(layout)
Example #2
0
    def __init__(self, title=None):
        super(TitleWidget, self).__init__()

        if sys.platform.startswith("darwin"):
            color1 = QColor(230, 230, 230, 255)
            color2 = QColor(177, 177, 177, 255)

            gradient = QLinearGradient()
            gradient.setStart(0, 0)
            gradient.setFinalStop(0, TitleWidget.TitleHeight)
            gradient.setColorAt(0, color1)
            gradient.setColorAt(1, color2)

            brush = QBrush(gradient)
            palette = QPalette()
            palette.setBrush(QPalette.Background, brush)
            self.setPalette(palette)
            self.setAutoFillBackground(True)

        self.setMaximumHeight(TitleWidget.TitleHeight)
        self.setMinimumHeight(TitleWidget.TitleHeight)

        self.titleLabel = QLabel("", parent=self)
        font = self.titleLabel.font()
        font.setPixelSize(11)
        self.titleLabel.setFont(font)
        self.titleLabel.setAlignment(Qt.AlignCenter)
        self.titleLabel.setText(title)

        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.titleLabel)
        self.setLayout(layout)
Example #3
0
 def __init__(self, parent):
     self.parent = parent
     QWidget.__init__(self)
     self.setAutoFillBackground(True)
     bgCol = QPalette()
     bgCol.setColor(QPalette.Background, Qt.yellow)
     self.setPalette(bgCol)
     self.initUI()
 def initUI(self):
     self.addKeyHandler(16777216, self.escHandler)
     p = QPalette()
     p.setColor(QPalette.Background, QtGui.QColor(255, 255, 255))
     self.setPalette(p)
     self.setGeometry(0, 0, self._width, self._height)
     self.setWindowTitle('Projector Calibration')
     self.show()
	def initUI(self):
		self.addKeyHandler(16777216, self.escHandler)	   
		p = QPalette()
		p.setColor(QPalette.Background, QtGui.QColor(255,255,255))
		self.setPalette(p)
		self.setGeometry(0, 0, self._width, self._height)
		self.setWindowTitle('Projector Calibration')
		self.show()
 def paintEvent(self, e):
     p = QPalette()
     print self.width(), self.height()
     gradient = QtGui.QRadialGradient(self.width() / 2, self.height() / 2, min(self.width(), self.height()))
     gradient.setColorAt(0.7, QtGui.QColor(0, 0, 0))
     gradient.setColorAt(0.0, QtGui.QColor(0, 255, 0))
     p.setBrush(QPalette.Window, QtGui.QBrush(gradient))
     self.setPalette(p)
Example #7
0
 def __init__(self, parent):
     self.parent = parent
     QWidget.__init__(self)
     print "Application started"
     self.setAutoFillBackground(True)
     bgCol = QPalette()
     bgCol.setColor(QPalette.Background, Qt.black)
     self.setPalette(bgCol)
     self.initUI()
Example #8
0
 def initUI(self):
     posX, posY, sizeW, sizeH = s.GEOMETRY_MAINWIDOW
     self.setGeometry(posX, posY, sizeW, sizeH)
     self.setWindowTitle("Hospital Management System")
     palette = QPalette()
     palette.setBrush(QPalette.Background, QBrush(QPixmap(s.PATH_IMG_BG_LOGIN)))
     self.setPalette(palette)
     self.initButton()
     self.forDev()
Example #9
0
 def initButton(self):
     loader = QUiLoader()
     form = loader.load('RSC/loginUI/Widget_LoginUI.ui', self)
     self.user_id = form.findChild(QLineEdit, "lineEdit_username")
     self.password = form.findChild(QLineEdit, "lineEdit_password")
     self.login_button = form.findChild(QPushButton, "button_login")
     self.login_button.clicked.connect(self.logIn)
     palette = QPalette()
     palette.setBrush(QPalette.Background, QBrush(QPixmap(s.PATH_IMG_BG_LOGIN)))
     self.setPalette(palette)
 def paintEvent(self, e):
     p = QPalette()
     print self.width(), self.height()
     gradient = QtGui.QRadialGradient(self.width() / 2,
                                      self.height() / 2,
                                      min(self.width(), self.height()))
     gradient.setColorAt(0.7, QtGui.QColor(0, 0, 0))
     gradient.setColorAt(0.0, QtGui.QColor(0, 255, 0))
     p.setBrush(QPalette.Window, QtGui.QBrush(gradient))
     self.setPalette(p)
    def _init_ui(self, txt):
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)

        pal = QPalette()
        color = QColor()
        color.setNamedColor(self._window_bgcolor)
        color.setAlpha(255 * self._opacity)
        pal.setColor(QPalette.Background, color)

        self.setAutoFillBackground(True)
        self.setPalette(pal)

        wm, hm = 5, 5
        spacing = 8
        layout = QVBoxLayout()
        layout.setSpacing(spacing)
        layout.setContentsMargins(wm, hm, wm, hm)

        nlines, ts = self._generate_text(txt)

        qlabel = QLabel('\n'.join(ts))

        ss = 'QLabel {{color: {}; font-family:{}, sans-serif; font-size: {}px}}'.format(self._color,
                                                                                        self._font,
                                                                                        self._fontsize)
        qlabel.setStyleSheet(ss)
        layout.addWidget(qlabel)

        hlabel = QLabel('double click to dismiss')
        hlabel.setStyleSheet('QLabel {font-size: 10px}')

        hlayout = QHBoxLayout()

        hlayout.addStretch()
        hlayout.addWidget(hlabel)
        hlayout.addStretch()

        layout.addLayout(hlayout)

        self.setLayout(layout)

        font = QFont(self._font, self._fontsize)
        fm = QFontMetrics(font)

        pw = max([fm.width(ti) for ti in ts])
        ph = (fm.height() + 2) * nlines

        w = pw + wm * 2
        h = ph + (hm + spacing + 1) * 2

        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setFixedWidth(w)
        self.setFixedHeight(h)

        self.setMask(mask(self.rect(), 10))
Example #12
0
    def __init__(self):
        '''
        Constructor
        '''
        super(LoginDialog, self).__init__()
        formLayout = QFormLayout()
        
        self.input1 = QLineEdit()
        self.input2 = QLineEdit()
        self.input2.setEchoMode(QLineEdit.EchoMode.Password)

        self.input3 = QLineEdit()
        self.input3.setEchoMode(QLineEdit.EchoMode.Password)    
        
        self.cb = QComboBox()
        self.cb.addItems(["Sef stanice", "Radnik u centrali", "Radnik na naplatnom mestu", "Admin"])
        
        palete = QPalette()
        palete.setColor(self.backgroundRole(), Qt.black)
        self.setPalette(palete)
        self.setWindowTitle("Login")
        self.resize(370, 100)
        
        label2 = QLabel("<font color='White'>Username</font>")
        label3 = QLabel("<font color='White'>Password</font>")
        label4 = QLabel("<font color='White'>Registration key</font>")
        label5 = QLabel("<font color='White'>Role</font>")
        
        formLayout.addRow(label2, self.input1)
        formLayout.addRow(label3, self.input2)
    
        
        btnOK = QPushButton("Login")
        btnOK.clicked.connect(self.loginAction)
        btnCancel = QPushButton("Cancel")
        btnCancel.clicked.connect(self.reject)
        btnRegister = QPushButton("Register")
        btnRegister.clicked.connect(self.registerAction)
        
        
        group = QDialogButtonBox()
        group.addButton(btnOK, QDialogButtonBox.AcceptRole)
        group.addButton(btnCancel, QDialogButtonBox.RejectRole)
        
        
        formLayout.addRow(group)
        formLayout.addRow(label4, self.input3)
        formLayout.addRow(label5, self.cb)
        formLayout.addWidget(btnRegister)
        
        self.result = None
        self.setLayout(formLayout)
Example #13
0
 def __init__(self, parent=None):
     super(Document, self).__init__(parent)
     self._shapeList = []
     
     self.mousePressIndex = -1
     self.mousePressOffset = 0
     
     self.setAutoFillBackground(True)
     self.setBackgroundRole(QPalette.Base)
     
     pal = QPalette()
     pal.setColor(QPalette.HighlightedText, Qt.red)
     self.setPalette(pal)
class LoggerTextEdit(QTextEdit):
    """A multiline text field showing log messages."""

    def __init__(self):
        super(LoggerTextEdit, self).__init__()
        self.pal = QPalette()
        textc = QColor(255, 255, 255)
        self.pal.setColor(QPalette.Text, textc)
        self.setPalette(self.pal)
        self.setReadOnly(True)

    def write(self, text):
        """Simulate LogHandler by having a write() method."""
        self.insertPlainText(text)
    def init(self, parent):
        """

        """
        if self.control is None:
            self.control = self.control_klass()

            if self.factory.bg_color:
                p = QPalette()
                p.setColor(QPalette.Base, self.factory.bg_color)
                self.control.setPalette(p)
            self.control.setReadOnly(True)

        # self.object.on_trait_change(self._on_clear, self.factory.clear)

        self.sync_value(self.factory.refresh, 'refresh', mode='from')
 def __init__(self):
     super(LoggerTextEdit, self).__init__()
     self.pal = QPalette()
     textc = QColor(255, 255, 255)
     self.pal.setColor(QPalette.Text, textc)
     self.setPalette(self.pal)
     self.setReadOnly(True)
Example #17
0
    def init(self, parent):
        '''

        '''
        if self.control is None:
            self.control = self.control_klass()

            if self.factory.bg_color:
                p = QPalette()
                p.setColor(QPalette.Base, self.factory.bg_color)
                self.control.setPalette(p)
            self.control.setReadOnly(True)

#        self.object.on_trait_change(self._on_clear, self.factory.clear)

        self.sync_value(self.factory.refresh, 'refresh', mode='from')
Example #18
0
def log(msg, level, msgbox=False, parent="auto", stack=None):
    """docstring for error"""

    if stack is None:
        stack = inspect.stack()[1][0]

    #print inspect.stack()
    #print stack
    #print inspect.getmodule(stack)


    if inspect.getmodule(stack) is None:
        mod = inspect.stack()[1][1]
    else:
        mod = inspect.getmodule(stack).__name__
    lineno = stack.f_lineno

    if mod == "__main__":
        mod = "__main__:" + os.path.basename(__main__.__file__)

    logging.log(level, msg, extra={"mod": mod, "line": lineno})

    if msgbox:
        if parent == "auto":
            qapp = QApplication.instance()
            if qapp is None:
                qapp = QApplication([])
                qapp.setStyle(QStyleFactory.create("plastique") )
                palette = QPalette(QColor(62, 62, 62), QColor(62, 62, 62))
                palette.setColor(palette.Highlight, QColor(255*0.6, 198*0.6, 0))
                qapp.setPalette(palette)
            parent = qapp.activeWindow()

        if level == logging.DEBUG:
            QMessageBox.info(parent, logging.getLevelName(level).capitalize(), msg)
        elif level == logging.INFO:
            QMessageBox.information(parent, logging.getLevelName(level).capitalize(), msg)
        elif level == logging.WARNING:
            QMessageBox.warning(parent, logging.getLevelName(level).capitalize(), msg)
        elif level == logging.ERROR:
            QMessageBox.critical(parent, logging.getLevelName(level).capitalize(), msg)
        elif level == logging.CRITICAL:
            QMessageBox.critical(parent, logging.getLevelName(level).capitalize(), msg)
Example #19
0
    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        if self.factory.readonly:
            self.control = QLineEdit( self.str_value, parent() )
            self.control.setReadOnly( True )
            self.set_tooltip()
        else:
            super( SimpleEditor, self ).init( parent )

        control = self.control
        pal     = QPalette( control.palette() )
        pal.setColor( QPalette.Base, self.ok_color )
        control.setPalette( pal )

        # Patch the type of the control to insert the DND event handlers.
        control.__class__ = type( _DropWidget.__name__,
                ( type( control ), ), dict( _DropWidget.__dict__ ) )

        control._side_editor = self
	def initUI(self):
		"""
		Initializes UI. Creates a horizontal layout
		to which buttons can be added.
		"""
		if self._osx:
			# Mimic the style of buttons underneath a list view
			gradient = QLinearGradient()
			gradient.setStart(0, 0)
			gradient.setFinalStop(0, self.Height)

			colorTop = QColor(250, 250, 250, 255)
			colorMid = QColor(244, 244, 244, 255)
			colorInBetween = QColor(238, 238, 238, 255)
			colorMidLow = QColor(234, 234, 234, 255)
			colorLow = QColor(239, 239, 239, 255)
			gradient.setColorAt(0, colorTop)
			gradient.setColorAt(0.45, colorMid)
			gradient.setColorAt(0.5, colorInBetween)
			gradient.setColorAt(0.55, colorMidLow)
			gradient.setColorAt(1, colorLow)

			brush = QBrush(gradient)
			palette = QPalette()
			palette.setBrush(QPalette.Background, brush)

			self.setAutoFillBackground(True)
			self.setPalette(palette)

		# Use a horizontal layout in which to keep
		# buttons. Initialize with an empty QWidget to
		# make the buttons align to the left
		if self.orientation == Qt.Horizontal:
			self.layout = QHBoxLayout()
		else:
			self.layout = QVBoxLayout()
		self.layout.setSpacing(0)
		self.layout.setContentsMargins(0, 0, 0, 0)
		self.layout.addWidget(QWidget())
		self.setLayout(self.layout)
    def initUI(self):
        """
		Initializes UI. Creates a horizontal layout
		to which buttons can be added.
		"""
        if self._osx:
            # Mimic the style of buttons underneath a list view
            gradient = QLinearGradient()
            gradient.setStart(0, 0)
            gradient.setFinalStop(0, self.Height)

            colorTop = QColor(250, 250, 250, 255)
            colorMid = QColor(244, 244, 244, 255)
            colorInBetween = QColor(238, 238, 238, 255)
            colorMidLow = QColor(234, 234, 234, 255)
            colorLow = QColor(239, 239, 239, 255)
            gradient.setColorAt(0, colorTop)
            gradient.setColorAt(0.45, colorMid)
            gradient.setColorAt(0.5, colorInBetween)
            gradient.setColorAt(0.55, colorMidLow)
            gradient.setColorAt(1, colorLow)

            brush = QBrush(gradient)
            palette = QPalette()
            palette.setBrush(QPalette.Background, brush)

            self.setAutoFillBackground(True)
            self.setPalette(palette)

        # Use a horizontal layout in which to keep
        # buttons. Initialize with an empty QWidget to
        # make the buttons align to the left
        if self.orientation == Qt.Horizontal:
            self.layout = QHBoxLayout()
        else:
            self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(QWidget())
        self.setLayout(self.layout)
Example #22
0
 def _bgcolor_changed(self):
     p = QPalette()
     p.setColor(QPalette.Base, self.bgcolor)
     self.control.setPalette(p)
 def setBgColor(self, color):
     """Set the background color of the log window."""
     pal = QPalette()
     pal.setColor(QPalette.Base, QColor(color))
     self.widget().setPalette(pal)
Example #24
0
 def _bgcolor_changed(self):
     p = QPalette()
     p.setColor(QPalette.Base, self.bgcolor)
     self.control.setPalette(p)
Example #25
0
    def _make_total_days_off_panel(self):

        widget = QFrame()
        widget.setObjectName('HorseRegularFrame')

        widget.setFrameShape(QFrame.Panel)
        widget.setFrameShadow(QFrame.Sunken)
        layout = QVBoxLayout()

        #layout.addWidget(QLabel(_("Days off to date")))
        self.day_off_total_duration_labels = dict()
        self.day_off_month_duration_labels = dict()
        self.day_off_labels = dict()

        self._day_off_table_model = QStandardItemModel(10, 3)
        self._day_off_table_model.setHorizontalHeaderLabels(
            [None, None, _("This\nmonth"),
             _("Before")])
        self.day_off_table_view = QTableView(None)
        self.day_off_table_view.setModel(self._day_off_table_model)

        # self.day_off_table_view.setHorizontalHeader(self.headers_view)
        self.day_off_table_view.verticalHeader().hide()
        self.day_off_table_view.setAlternatingRowColors(True)
        self.day_off_table_view.setEditTriggers(
            QAbstractItemView.NoEditTriggers)

        self.day_off_table_view.hide()

        row = 0
        for det in DayEventType.symbols():
            ndx = self._day_off_table_model.index(row, 0)
            self._day_off_table_model.setData(ndx, det.description,
                                              Qt.DisplayRole)

            ndx = self._day_off_table_model.index(row, 1)
            fg, bg = self.DAY_EVENT_PALETTE[det]
            self._day_off_table_model.setData(ndx, QBrush(bg),
                                              Qt.BackgroundRole)
            self._day_off_table_model.setData(ndx, QBrush(fg),
                                              Qt.TextColorRole)
            self._day_off_table_model.setData(ndx,
                                              DayEventType.short_code(det),
                                              Qt.DisplayRole)

            row += 1

        layout.addWidget(self.day_off_table_view)

        grid = QGridLayout()
        self.days_off_layout = grid
        grid.setColumnStretch(3, 1)
        row = 0

        grid.addWidget(QLabel(_('Year')), row, self.YEAR_EVENT_COLUMN)
        grid.addWidget(QLabel(_('Month')), row, self.MONTH_EVENT_COLUMN)
        row += 1

        for det in DayEventType.symbols():
            self.day_off_total_duration_labels[det] = QLabel("-")
            self.day_off_month_duration_labels[det] = QLabel("-")
            self.day_off_labels[det] = QLabel(det.description)

            hlayout = QHBoxLayout()

            sl = QLabel()
            fg, bg = self.DAY_EVENT_PALETTE[det]

            def to_html_rgb(color):
                i = color.red() * 256 * 256 + color.green() * 256 + color.blue(
                )
                return "#{:06X}".format(i)

            p = QPalette()
            p.setColor(QPalette.Window, QColor(bg))
            p.setColor(QPalette.WindowText, QColor(fg))
            sl.setPalette(p)
            sl.setAlignment(Qt.AlignCenter)
            sl.setStyleSheet("border: 2px solid black; background: {}".format(
                to_html_rgb(QColor(bg))))

            t = DayEventType.short_code(det)
            mainlog.debug(t)
            sl.setAutoFillBackground(True)
            sl.setText(t)

            grid.addWidget(sl, row, 0)
            grid.addWidget(self.day_off_labels[det], row, 1)
            grid.addWidget(self.day_off_total_duration_labels[det], row,
                           self.YEAR_EVENT_COLUMN)
            grid.addWidget(self.day_off_month_duration_labels[det], row,
                           self.MONTH_EVENT_COLUMN)

            hlayout.addStretch()

            row += 1

        layout.addLayout(grid)
        layout.addStretch()

        self.day_off_table_view.resizeColumnsToContents()
        # self.day_off_table_view.setMinimumWidth( self.day_off_table_view.width())
        # self.day_off_table_view.resize( self.day_off_table_view.minimumWidth(),
        #                                 self.day_off_table_view.minimumHeight(),)

        widget.setLayout(layout)
        return widget
Example #26
0
 def initUI(self):
     self.addKeyHandler(16777216, self.escHandler)
     p = QPalette()
     p.setColor(QPalette.Background, QtGui.QColor(0, 0, 0))
     self.setPalette(p)
     self.showFullScreen()
    def __init__(self, parent=None, filePath=''):
        """Default class constructor."""
        super(MDISubWindow_TextEdit, self).__init__(parent)

        print(filePath)
        self.filePath = filePath
        self.fileName = os.path.basename(os.path.abspath(filePath))
        self.fileExt = os.path.splitext(self.fileName)[1]

        if not filePath:
            self.setWindowTitle('Untitled[*]')
            parent.setWindowIcon(QIcon(gIconDir + os.sep + 'new.png'))
        else:
            f = open(filePath, 'r')
            txt = f.read()
            f.close()
            self.setText(txt)

            self.setWindowTitle('%s[*]' % self.fileName)

            # TODO: This is changing all the subwindows icons. We want individual icons based on filetype...?
            if self.fileExt in ('.py', '.pyw'):
                parent.setWindowIcon(QIcon(gIconDir + os.sep + 'pyscript.png'))
            else:
                parent.setWindowIcon(QIcon(gIconDir + os.sep + 'new.png'))

        monoFont = QFont('Courier New')
        monoFont.setFixedPitch(True)
        self.setFont(monoFont)
        self.setWordWrapMode(QTextOption.NoWrap)
        ## self.setTextBackgroundColor(QColor('#000000'))
        ## self.setTextColor(QColor('#FFFFFF'))
        self.setCursorWidth(2)
        self.CreateActions()

        self.zoomLevel = 0

        gMainWin.action_Edit_Cut.setEnabled(False)
        gMainWin.action_Edit_Copy.setEnabled(False)
        self.copyAvailable.connect(gMainWin.action_Edit_Cut.setEnabled)
        self.copyAvailable.connect(gMainWin.action_Edit_Copy.setEnabled)
        # Handle the Context Menu Entries Also.
        self.action_Edit_Undo.setEnabled(False)
        self.action_Edit_Redo.setEnabled(False)
        self.action_Edit_Cut.setEnabled(False)
        self.action_Edit_Copy.setEnabled(False)
        self.undoAvailable.connect(self.action_Edit_Undo.setEnabled)
        self.redoAvailable.connect(self.action_Edit_Redo.setEnabled)
        self.copyAvailable.connect(self.action_Edit_Cut.setEnabled)
        self.copyAvailable.connect(self.action_Edit_Copy.setEnabled)

        self.document().contentsChanged.connect(self.TheDocumentWasModified)

        # self.show()
        # self.showMaximized()
        # self.setFocusPolicy(Qt.WheelFocus)
        ##### self.setFocus() # This makes the MDIArea go into SubWindowView...?

        self.gCornerWidget = QToolButton(self)
        # self.gCornerWidgetToolTip = QToolTip()
        QToolTip.setFont(QFont('SansSerif', 10))
        br = QBrush(QPixmap(gImgDir + os.sep + 'texture-spirals.png'))
        pal = QPalette()
        # pal.setBrush(QPalette.Active, QPalette.Base, br)
        # pal.setColor(QPalette.Background, QColor('#FF8000'))
        pal.setColor(QPalette.ColorGroup.Inactive,
                     QPalette.ColorRole.ToolTipBase,
                     QColor(EMBROIDERBLUE2))
        QToolTip.setPalette(QPalette(pal))
        self.action_Edit_SelectAll.setToolTip('This is a <b>QWidget</b> widget')

        self.gCornerWidget.setDefaultAction(self.action_Edit_SelectAll)
        self.setCornerWidget(self.gCornerWidget)
        # We want to show the corner widget no matter what so...
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
	def initUI(self):
		#self.addKeyHandler(16777216, self.escHandler)
		p = QPalette()
		p.setColor(QPalette.Background, QtGui.QColor(0,0,0))
		self.setPalette(p)
		self.showFullScreen()
Example #29
0
def f(*args, **kwargs)):
	# args is a tuple
	# kwargs is a dict
	
# or you can do the reverse and unravel a tuple and dict to pass into a function
mylist = [1,2,3]
foo(*mylist)
mydict = { 'a' : 1, 'b' : 2 }
bar(**mydict)
	
	

# create a new class that sucks in dict values
class Struct:
	def __init__(self, **kwargs): 
		self.__dict__.update(kwargs)
	def assimilate(self, **kwargs): 
		self.__dict__.update(kwargs)


'''
Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

    the innermost scope, which is searched first, contains the local names
    the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
    the next-to-last scope contains the current module�s global names (__main__ for example)
    the outermost scope (searched last) is the namespace containing built-in names 

If a name is declared global, then all references and assignments go directly to the middle scope containing the module�s global names.
Otherwise, all variables found outside of the innermost scope are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).

'''

g = 0

def increment():
	# global variables can be accessed but if you are going to change them the global declaration is required.
    global g
    g += 1

amalgamated_dict = dict(a, **award_dict) instead of dict(d1.items() + d2.items())


# You would do this:
'one 1 two 2' == "one {} two {}".format(1, 2) == "one {2} two {0}".format(2,3,1)


# Or this:
print "foo is {bar}".format(bar='bar')

# Or this:
print "foo is {[0]}".format(('bar','joy'))

# Or even this:
print "foo is %(foo)s" % {'foo':'bar'}

r"look\n\"" # 'raw string literal' treats backslash as a backslash, except to escape the quote character


def main():
    pass

if __name__ == "__main__":
    main()

dict(zip('123','abc')) == {'1': 'a', '2': 'b', '3': 'c'}


from functools import partial

def myfunc(a,b,c):
	return (a,b,c)

# partially-apply function (sometimes referred to incorrectly as curry technique, see boost:bind)
f1 = partial(myfunc, 1, 2)
f1(3) == (1,2,3)

for i, colour in enumerate(colours):


from PySide import QtCore, QtGui
from PySide.QtGui import QPalette
from PySide.QtCore import Qt
import sys
app = QtGui.QApplication(sys.argv)
w = QtGui.QDialog()
wc = QtGui.QComboBox(w)

pal.setColor(QPalette.backgroundRole(), Qt::blue);


w.show()
app.exec_()


import condition_evaluator
A = { 'a' : 3, 'b': 4}
B = ['a', 'b', 'c', 'd']
# also include faults that haven't had any occurances
all_fault_counts = dict([(f, A.get(f,0)) for f in B])
# is { 'a':3, 'b':4, 'c':0, 'd':0 }
sorted_faults = sorted(all_fault_counts, key=condition_evaluator.itemgetter(1), reverse=True)
# is [('b', 4), ('a', 3), ('c', 0), ('d', 0)]
labels, values = [[t[i] for t in sorted_faults] for i in (0,1)]
# split the list of tuples up into ['b', 'a', 'c', 'd'] and [4, 3, 0, 0]


try:
    # This causes an exception.
    f = open("abc")
except:
    print("Except hit")
    # Raise the exception again.
    raise



# list view of checkable items
from PySide.QtCore import *
from PySide.QtGui import *
import sys
from random import randint

app = QApplication(sys.argv)

model = QStandardItemModel()

for n in range(10):
    item = QStandardItem('Item %s' % randint(1, 100))
    item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)

    check = Qt.Checked if randint(0, 1) == 1 else Qt.Unchecked

    item.setData(check, Qt.CheckStateRole)
    model.appendRow(item)

view = QListView()
view.setModel(model)

view.show()
app.exec_()

# 2 ways to use QMessageBox and similar
ret = QMessageBox.warning(self, "My Application", "Save changes?", QMessageBox.Save | QMessageBox.Cancel,
                                   QMessageBox.Save)
# Advanced Usage
msgBox = QMessageBox()
connectButton = msgBox.addButton("Connect", QMessageBox.ActionRole)
abortButton = msgBox.addButton(QMessageBox.Abort)
msgBox.exec_()
if msgBox.clickedButton() == connectButton:
     # connect
elif msgBox.clickedButton() == abortButton:
    # abort

	
import sys	
from PySide import QtGui, QtCore

try:
	app = QtGui.QApplication(sys.argv)

	myappTranslator = QtCore.QTranslator()
	myappTranslator.load("C:\Dropbox\r\haymaker_v0.11\i18n\en_US")
	app.installTranslator(myappTranslator)

	mainwindow = QtGui.QDialog()
	mainwindow.show()
	msg = app.tr("foobar")
	print msg
	sys.exit(app.exec_())
except Exception as e:
	print e
Example #30
0
 def _set_background ( self, col ):
     le  = self.control.lineEdit()
     pal = QPalette( le.palette() )
     pal.setColor( QPalette.Base, col )
     le.setPalette( pal )
    def __init__(self, parent=None, filePath=''):
        """Default class constructor."""
        super(MDISubWindow_TextEdit, self).__init__(parent)

        print(filePath)
        self.filePath = filePath
        self.fileName = os.path.basename(os.path.abspath(filePath))
        self.fileExt = os.path.splitext(self.fileName)[1]

        if not filePath:
            self.setWindowTitle('Untitled[*]')
            parent.setWindowIcon(QIcon(gIconDir + os.sep + 'new.png'))
        else:
            f = open(filePath, 'r')
            txt = f.read()
            f.close()
            self.setText(txt)

            self.setWindowTitle('%s[*]' % self.fileName)

            # TODO: This is changing all the subwindows icons. We want individual icons based on filetype...?
            if self.fileExt in ('.py', '.pyw'):
                parent.setWindowIcon(QIcon(gIconDir + os.sep + 'pyscript.png'))
            else:
                parent.setWindowIcon(QIcon(gIconDir + os.sep + 'new.png'))

        monoFont = QFont('Courier New')
        monoFont.setFixedPitch(True)
        self.setFont(monoFont)
        self.setWordWrapMode(QTextOption.NoWrap)
        ## self.setTextBackgroundColor(QColor('#000000'))
        ## self.setTextColor(QColor('#FFFFFF'))
        self.setCursorWidth(2)
        self.CreateActions()

        self.zoomLevel = 0

        gMainWin.action_Edit_Cut.setEnabled(False)
        gMainWin.action_Edit_Copy.setEnabled(False)
        self.copyAvailable.connect(gMainWin.action_Edit_Cut.setEnabled)
        self.copyAvailable.connect(gMainWin.action_Edit_Copy.setEnabled)
        # Handle the Context Menu Entries Also.
        self.action_Edit_Undo.setEnabled(False)
        self.action_Edit_Redo.setEnabled(False)
        self.action_Edit_Cut.setEnabled(False)
        self.action_Edit_Copy.setEnabled(False)
        self.undoAvailable.connect(self.action_Edit_Undo.setEnabled)
        self.redoAvailable.connect(self.action_Edit_Redo.setEnabled)
        self.copyAvailable.connect(self.action_Edit_Cut.setEnabled)
        self.copyAvailable.connect(self.action_Edit_Copy.setEnabled)

        self.document().contentsChanged.connect(self.TheDocumentWasModified)

        # self.show()
        # self.showMaximized()
        # self.setFocusPolicy(Qt.WheelFocus)
        ##### self.setFocus() # This makes the MDIArea go into SubWindowView...?

        self.gCornerWidget = QToolButton(self)
        # self.gCornerWidgetToolTip = QToolTip()
        QToolTip.setFont(QFont('SansSerif', 10))
        br = QBrush(QPixmap(gImgDir + os.sep + 'texture-spirals.png'))
        pal = QPalette()
        # pal.setBrush(QPalette.Active, QPalette.Base, br)
        # pal.setColor(QPalette.Background, QColor('#FF8000'))
        pal.setColor(QPalette.ColorGroup.Inactive,
                     QPalette.ColorRole.ToolTipBase, QColor(EMBROIDERBLUE2))
        QToolTip.setPalette(QPalette(pal))
        self.action_Edit_SelectAll.setToolTip(
            'This is a <b>QWidget</b> widget')

        self.gCornerWidget.setDefaultAction(self.action_Edit_SelectAll)
        self.setCornerWidget(self.gCornerWidget)
        # We want to show the corner widget no matter what so...
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)