class plotScroller: def update_val(self, proc): d=str(self.scl.value()) self.v.setText(d) if proc != None: proc(self.scl.value()) def __init__(self, master, text, geo, proc=None, lim=(0,100,1)): self.scl=QScrollBar(Qt.Horizontal, master) self.scl.resize(geo[2]-50,geo[3]) self.scl.move(geo[0]+50,geo[1]) self.scl.setMinimum(lim[0]) self.scl.setMaximum(lim[1]) self.scl.setSingleStep(lim[2]) self.scl.valueChanged.connect(lambda: self.update_val(proc)) q=QLabel(master) q.move(geo[0],geo[1]+10) q.resize(50,20) q.setText(text) self.v=QLabel(master) self.v.move(geo[2]+10,geo[1]+10) self.v.resize(50,20) self.v.setText(str(self.scl.value())) def setValue(self, v): self.scl.setValue(v)
def createBottomRightGroupBox(self): self.bottomRightGroupBox = QGroupBox("Audio Speed") lineEdit = QLineEdit('s3cRe7') lineEdit.setEchoMode(QLineEdit.Password) spinBox = QSpinBox(self.bottomRightGroupBox) spinBox.setValue(50) slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox) scrollBar.setValue(60) dial = QDial(self.bottomRightGroupBox) dial.setValue(30) dial.setNotchesVisible(True) layout = QGridLayout() layout.addWidget(spinBox, 1, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 1) self.bottomRightGroupBox.setLayout(layout)
def createTopRightGroupBox(self): self.topRightGroupBox = QGroupBox("Group 2") togglePushButton = QPushButton("Toggle Push Button") togglePushButton.setCheckable(True) togglePushButton.setChecked(True) slider = QSlider(Qt.Horizontal, self.RadiiScaleGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.RadiiScaleGroupBox) scrollBar.setValue(60) dial = QDial(self.RadiiScaleGroupBox) dial.setValue(30) dial.setNotchesVisible(True) layout = QVBoxLayout() layout.addWidget(self.openFileNameButton) layout.addWidget(togglePushButton) layout.addWidget(self.flatPushButton) layout.addWidget(slider) layout.addWidget(scrollBar) layout.addWidget(dial) layout.addStretch(1) self.topRightGroupBox.setLayout(layout)
def createBottomRightGroupBox(self): self.bottomRightGroupBox = QGroupBox("Group 3") self.bottomRightGroupBox.setCheckable(True) self.bottomRightGroupBox.setChecked(True) lineEdit = QLineEdit('s3cRe7') lineEdit.setEchoMode(QLineEdit.Password) spinBox = QSpinBox(self.bottomRightGroupBox) spinBox.setValue(50) dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox) dateTimeEdit.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox) scrollBar.setValue(60) dial = QDial(self.bottomRightGroupBox) dial.setValue(30) dial.setNotchesVisible(True) layout = QGridLayout() layout.addWidget(lineEdit, 0, 0, 1, 2) layout.addWidget(spinBox, 1, 0, 1, 2) layout.addWidget(dateTimeEdit, 2, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 1) layout.setRowStretch(5, 1) self.bottomRightGroupBox.setLayout(layout)
def group4(window): groupbox = QGroupBox("Group 3") groupbox.setCheckable(True) groupbox.setChecked(True) input = QLineEdit("firmanslur", window) input.setEchoMode(QLineEdit.Password) spin = QSpinBox(window) spin.setValue(50) tanggal = QDateTimeEdit(window) tanggal.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal, window) slider.setValue(50) scrollBar = QScrollBar(Qt.Horizontal, window) scrollBar.setValue(60) dial = QDial(window) dial.setValue(30) dial.setNotchesVisible(True) layout = QGridLayout() layout.addWidget(input, 0, 0, 1, 2) layout.addWidget(spin, 1, 0, 1, 2) layout.addWidget(tanggal, 2, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 1) layout.setRowStretch(5, 1) groupbox.setLayout(layout) return groupbox
class ContentHolder(QScrollArea): def __init__(self, superEl): self.superEl = superEl super(ContentHolder, self).__init__() self.scrollBar = QScrollBar() self.scrollBar.setCursor(Qt.PointingHandCursor) self.setVerticalScrollBar(self.scrollBar) # self.setCursor() self.content = Content(self) self.setWidget(self.content) with open(f"{PATH}/src/style/scrollbar.qss", "r", encoding="utf8") as f: qssContent = f.read() self.setStyleSheet(qssContent) # self.scrollBar.valueChanged.connect(self.fff) # def fff(self): # print(self.scrollBar.value()) # def enterEvent(self, QEvent): # self.superEl.entered = True # self.active() # def leaveEvent(self, QEvent): # self.superEl.entered = False # self.disActive() def active(self): self.content.setStyleSheet( f"background-color: {config.colors.contentDisplayBg}") # self.contentHolder.scrollBar.setValue(0) def disActive(self): self.content.setStyleSheet( f"background-color: {config.colors.contentBg}") def setScrollBarValue(self, n): # print(1) # h=self.height() # l = self.content.bangumiChapters.__len__() # ratio = (n - 1)/l # mi = self.scrollBar.minimum() # m = self.scrollBar.maximum() # value = ratio * m + h/2 - (m / l)/2 # self.scrollBar.setValue(int(value)) # m = self.scrollBar.maximum() # l = self.content.bangumiChapters.__len__() # self.scrollBar.setValue(int((n/l) * m + self.height()/2)) self.scrollBar.setValue(n * 106 + 6)
def createBottomRightGroupBox(self): '''Create a checkable group widget useful in the case of form login etc''' self.bottomRightGroupBox = QGroupBox("Group 3") self.bottomRightGroupBox.setCheckable( True) # sets the state aware mode self.bottomRightGroupBox.setChecked( True) # sets the default state to active # # create the required widgets # a lineEdit Widget for password entry. Activate the security by setEchoMode() # a spinBox Widget which lets the field change using scroll # a Date Time Edit Widget # a Slider Widget responsive to scroll as well as press and move # a Scroll Widget responsive to scroll as well as press and move # a Dial Widget responsive to scroll as well as press and move # lineEdit = QLineEdit('s3cRe7') lineEdit.setEchoMode(QLineEdit.Password) spinBox = QSpinBox(self.bottomRightGroupBox) spinBox.setValue(25) dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox) dateTimeEdit.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox) scrollBar.setValue(60) dial = QDial(self.bottomRightGroupBox) dial.setValue(30) dial.setNotchesVisible(True) # # create the internal layout of the group Widget # layout = QGridLayout() layout.addWidget(lineEdit, 0, 0, 1, 3) layout.addWidget(spinBox, 1, 0, 1, 2) layout.addWidget(dateTimeEdit, 2, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 2) layout.setRowStretch(50, 1) # ?? whatdoes RowStretch do? self.bottomRightGroupBox.setLayout(layout)
class QConnectionView(QWidget): def __init__(self, parent=None): '''Initialization of the QMatrixView. Arguments --------- parent : QWidget The parent argument is sent to the QWidget constructor. ''' super().__init__(parent) self._inputScrollBar = QScrollBar(Qt.Vertical) self._inputScrollBar.setFocusPolicy(Qt.StrongFocus) self._inputScrollBar.setMaximum(0) self._inputScrollBar.setValue(0) self._connections = QConnectionDisplay() self._outputScrollBar = QScrollBar(Qt.Vertical) self._outputScrollBar.setFocusPolicy(Qt.StrongFocus) self._outputScrollBar.setMaximum(0) self._outputScrollBar.setValue(0) layout = QHBoxLayout() layout.addWidget(self._inputScrollBar) layout.addWidget(self._connections) layout.addWidget(self._outputScrollBar) self.setLayout(layout) self._inputScrollBar.valueChanged.connect( self._connections.setInputOffset) def setActivation(self, input: np.ndarray, output: np.ndarray) -> None: self._connections.setActivation(input, output) self._inputScrollBar.setMaximum( max( self._connections.getInputHeight() - self._connections.height(), 0)) self._inputScrollBar.setValue(self._connections.getInputOffset()) self._inputScrollBar.setPageStep(self._connections.height())
class DollWidget(QWidget): def __init__(self, usbcom=None, target='0.0.0.0', port=0, name='Uno_Doll'): super(DollWidget, self).__init__() self.name = name self.usbcom = usbcom self.target = target self.port = port self.initUI() def setName(self, name): self.name = name def setValue(self, value): self.timeline.setValue(value) self.eyebrowLine.setValue(value) self.eyeLine.setValue(value) self.earLine.setValue(value) self.mouseLine.setValue(value) def setSlider(self, value): if value > 0.8 * self.relativeMaximum: self.relativeMaximum = 1.2 * self.relativeMaximum self.slider.setValue(int(100 * value / self.relativeMaximum)) def initUI(self): self.mode = 0 self.time = 0 self.eyebrowEmotion = open('eyebrow.dqbe', 'w+') self.eyebrowEmotion.seek(0) self.eyeEmotion = open('eye.dqbe', 'w+') self.eyeEmotion.seek(0) self.earEmotion = open('ear.dqbe', 'w+') self.earEmotion.seek(0) self.mouseEmotion = open('mouse.dqbe', 'w+') self.mouseEmotion.seek(0) self.file = open('emoji.dqpe', 'a+') self.file.seek(0) '''mode 1 as play. mode 2 as record. mode 3 as stop. mode 4 as save.''' self.thisDoll = QCheckBox(self.name, self) self.eyebrow = QCheckBox('eyebrow', self) self.eye = QCheckBox('eye', self) self.ear = QCheckBox('ear', self) self.mouse = QCheckBox('mouse', self) self.playBtn = QPushButton('Play', self) self.recordBtn = QPushButton('Record', self) self.stopBtn = QPushButton('Stop', self) self.saveBtn = QPushButton('Save', self) self.timeline = TimeLine(scale=True) self.eyebrowLine = TimeLine(scale=False, emotionPool=self.eyebrowEmotion, types='eyebrow') self.eyeLine = TimeLine(scale=False, emotionPool=self.eyeEmotion, types='eye') self.earLine = TimeLine(scale=False, emotionPool=self.earEmotion, types='ear') self.mouseLine = TimeLine(scale=False, emotionPool=self.mouseEmotion, types='mouse') self.slider = QScrollBar(Qt.Horizontal) self.slider.setMinimum(0) self.slider.setMaximum(100) self.relativeMaximum = 15 self.slider.setValue(0) self.slider.valueChanged.connect(self.valueChange) self.playBtn.clicked.connect(self.handlePlayBtn) self.stopBtn.clicked.connect(self.handleStopBtn) self.recordBtn.clicked.connect(self.handleRecordBtn) self.saveBtn.clicked.connect(self.handleSaveBtn) self.thisDoll.stateChanged.connect( lambda: self.handleCheck(self.thisDoll)) dollcmd.setComPort(self.usbcom) #UI layout = QGridLayout(self) layout.addWidget(self.playBtn, 0, 0, 1, 1) layout.addWidget(self.recordBtn, 0, 1, 1, 1) layout.addWidget(self.stopBtn, 0, 2, 1, 1) layout.addWidget(self.saveBtn, 0, 3, 1, 1) layout.addWidget(self.thisDoll, 1, 0, 1, 1) layout.addWidget(self.eyebrow, 2, 1, 1, 1) layout.addWidget(self.eye, 3, 1, 1, 1) layout.addWidget(self.ear, 4, 1, 1, 1) layout.addWidget(self.mouse, 5, 1, 1, 1) scroll = QScrollArea() scroll.setWidgetResizable(True) self.scrollContent = QWidget(scroll) scrollLayout = QVBoxLayout(self.scrollContent) self.scrollContent.setLayout(scrollLayout) scrollLayout.addWidget(self.timeline) scrollLayout.addWidget(self.eyebrowLine) scrollLayout.addWidget(self.eyeLine) scrollLayout.addWidget(self.earLine) scrollLayout.addWidget(self.mouseLine) scroll.setWidget(self.scrollContent) layout.addWidget(self.slider, 0, 4, 1, 7) layout.addWidget(self.scrollContent, 1, 4, 5, 7) self.show() def valueChange(self): s = self.slider.value() value = (s * self.relativeMaximum * 0.01) self.setValue(value) if self.mode != 1 and self.mode != 2 and self.mode != 4: self.time = value * 20 def handleCheck(self, this): if this.isChecked(): state = Qt.Checked else: state = Qt.Unchecked self.eye.setCheckState(state) self.eyebrow.setCheckState(state) self.ear.setCheckState(state) self.mouse.setCheckState(state) def handlePlayBtn(self): self.mode = 1 self.handleIO() def handleStopBtn(self): self.mode = 3 def handleRecordBtn(self): self.mode = 2 self.handleIO() def handleSaveBtn(self): self.mode = 4 self.handleIO() ''' eyebrow and eye jd1[0] 1023 = left, 0 = right jd1[1] 1023 = up. , 0 = down ear 1023. = up, 0 = down ''' def handleIO(self): if self.mode == 1: data = self.file.readline() #dollcmd.sendUDP() self.time += 1 self.setValue(self.time * 0.05) self.setSlider(self.time * 0.05) QTimer.singleShot(50, self.handleIO) if self.mode == 2: data = dollcmd.handleIOData() self.file.write(data) #dollcmd.sendUDP(data) if '\n' in data: self.eyebrowEmotion.seek(self.time * 12) self.eyeEmotion.seek(self.time * 12) self.earEmotion.seek(self.time * 12) self.mouseEmotion.seek(self.time * 12) lists = data.replace('\n', '').split(',') #ear if int(lists[0]) > 512: i = 0 else: i = 1 i *= 3 if int(lists[1]) > 512: i += 0 else: i += 1 self.earEmotion.write('{}@{}\n'.format( str(self.time).zfill(8), str(i))) #ear #eyebrow if int(lists[2]) > 682: i = 0 elif int(lists[2]) > 341: i = 1 else: i = 2 i *= 3 if int(lists[3]) > 682: i += 0 elif int(lists[3]) > 341: i += 1 else: i += 2 self.eyebrowEmotion.write('{}@{}\n'.format( str(self.time).zfill(8), str(i))) #eyebrow #eye if int(lists[6]) > 682: i = 0 elif int(lists[6]) > 341: i = 1 else: i = 2 i *= 3 if int(lists[7]) > 682: i += 0 elif int(lists[7]) > 341: i += 1 else: i += 2 self.eyeEmotion.write('{}@{}\n'.format( str(self.time).zfill(8), str(i))) #eye #mouse if int(lists[10]) > 682: i = 0 elif int(lists[10]) > 341: i = 1 else: i = 2 i *= 3 if int(lists[11]) > 682: i += 0 elif int(lists[11]) > 341: i += 1 else: i += 2 self.mouseEmotion.write('{}@{}\n'.format( str(self.time).zfill(8), str(i))) #mouse self.time += 1 self.setValue(self.time * 0.05) self.setSlider(self.time * 0.05) QTimer.singleShot(50, self.handleIO) if self.mode == 3: pass if self.mode == 4: pass def mousePressEvent(self, event): pass def mouseMoveEvent(self, event): pass
class dicomImage2DdisplayWidget(QWidget): addSeedsSignal = pyqtSignal(bool) def __init__(self, **kwargs): super(dicomImage2DdisplayWidget, self).__init__() self._face = kwargs.get('face', 0) self._datas = kwargs.get('datas', 0) self._Spacing = kwargs.get('spacing', None) self._low_hu = kwargs.get("low_hu", -1150) self._high_hu = kwargs.get("high_hu", 3250) self._axis = 0 #===============Seeds information============================ self.seedsColors = [] self.baseImageSize = 512 self.regionDrawMod = 0 self.drawLayer = [] #===============Regioin draw tool parmeter=================== self.drawPanterbegin = QPoint() self.drawPanterEnd = QPoint() self.posX = 0 self.posY = 0 #===============Init UI====================================== self.initUI() def initUI(self): self.setGeometry(0, 0, self.baseImageSize, self.baseImageSize) self.viewLayout = None self.imLable = QLabel(self) self.imLable.setScaledContents(True) self.imData = None self.topLable = QLabel(self) self.downLable = QLabel(self) self.imLable.resize(self.width(), self.height()) self.initDicomParameter() pass def initDicomParameter(self): #============================SetDataParameter=========================== self._color_table = [qRgb(i, i, i) for i in range(64)] self.datas = self._datas.copy() self.faceWindowV = self.faceWindowH = max(self.datas.shape) #============================ChangeFaceSize============================= self.xSpacing, self.ySpacing, self.zSpacing = self._Spacing #============================OperationMod=============================== self.OperationMod = 0 self.facePlane = ['mainFaceplane', 'leftFaceplane', 'frontFaceplane'] self.idxSlice = 100 self.currentFace = self.facePlane[self._face] #============================RegionGrowingParameter===================== self.PosXY = [150, 75] # self.seedList = [(self.PosXY[0], self.PosXY[1])] self.seedList = [] self.seedSelectNum = 0 self.LowAndUpper = [10, 3000] self.regionArea = [] self.regionDrawSize = 5 self.idxSlicelimt = self.datas.shape[0] # print(self.datas.shape[0]) #======================================================================= self.initOperationButton() self.initDisplayfacePlane() self.choiceOpreationMod() pass def initOperationButton(self): self.facePlanes = QComboBox(self) self.facePlanes.addItem(self.facePlane[0]) self.facePlanes.addItem(self.facePlane[1]) self.facePlanes.addItem(self.facePlane[2]) self.facePlanes.setCurrentIndex(self._face) # self.facePlanes.activated[str].connect(self.faceItem_Choice) self.facePlanes.currentTextChanged.connect(self.faceItem_Choice) self.facePlanes.keyPressEvent = self.customComboxKeyEvent self.facePlanes.move((self.width() - self.facePlanes.width()), 0) #==================================Active keyBoard event without combobox======================= # shorcut = QShortcut(QKeySequence(Qt.Key_F), self.facePlanes, activated=self.useforTestKeyEvent) #=============================================================================================== #================================== Contrul region seed up and low range ======================= regionWide = QRangeSlider(self) regionWide.setMax(255) regionWide.setMin(0) regionWide.setStart(150) regionWide.setEnd(255) regionWide.setRange(0, 255) regionWide.setDrawValues(True) regionWide.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);') regionWide.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #8EE5EE, stop:1 #393);') regionWide.startValueChanged.connect(self.rangeSliderStartVolue) regionWide.endValueChanged.connect(self.rangeSliderEndVolue) #=============================================================================================== self.modCombox = QComboBox(self) self.modCombox.addItem('Normal') self.modCombox.addItem('Region') self.modCombox.setCurrentIndex(self.OperationMod) # self.modCombox.activated[str].connect(self.mod_Choice) self.modCombox.currentTextChanged.connect(self.mod_Choice) self.modCombox.keyPressEvent = self.customComboxKeyEvent self.modCombox.move((self.width() - self.facePlanes.width() - self.modCombox.width()), 0) self.layerScrollBar = QScrollBar(Qt.Horizontal, self) self.layerScrollBar.setGeometry(0, 0, 128, 5) self.layerScrollBar.setMinimum(0) self.layerScrollBar.setMaximum(min(self.datas.shape)) self.layerScrollBar.setValue(0) self.layerScrollBar.sliderMoved.connect(self.selectLayer) self.BaseBoxLayout = QBoxLayout(QBoxLayout.TopToBottom) self.BaseBoxLayout.addWidget(self.layerScrollBar, 0) self.BaseBoxLayout.addWidget(regionWide, 1) self.BaseBoxLayout.setAlignment(Qt.AlignTop) self.secondBoxLayout = QBoxLayout(QBoxLayout.LeftToRight) self.secondBoxLayout.addLayout(self.BaseBoxLayout) self.secondBoxLayout.addWidget(self.modCombox) self.secondBoxLayout.addWidget(self.facePlanes) self.secondBoxLayout.setAlignment(Qt.AlignTop) self.groupbox = QGroupBox(self) self.groupbox.setGeometry(28, -64, 512, 64) self.groupbox.setLayout(self.secondBoxLayout) self.showButton = QPushButton(self) self.showButton.setGeometry(0, 0, 16, 16) self.showButton.clicked.connect(self.playAnimation) self.initAnimation() pass def setGroup_pos(self, apos): self.groupbox.move(apos.x(), apos.y()) pass def setSeedsColor(self, lists): # self.seedList.clear() # self.seedsColors.clear() # for i in range(0, len(colorList)): # self.seedsColors.append(colorList[i][0]) # self.seedList.append(colorList[i][1]) self.seedsColors.append(lists[0]) self.seedList.append(lists[1]) print('seedList:', self.seedList) pass def selectSeedinList(self, num): # tmpS = self.seedList[num] # tmpC = self.seedsColors[num] self.seedSelectNum = num # print(self.seedsColors) # print(self.seedList) # print('number is :', num) # print(tmpC, tmpS) pass def removeSeedinList(self, num): self.seedList.remove(self.seedList[num]) self.choiceDisplayMod() pass def rangeSliderStartVolue(self, event): self.LowAndUpper[0] = event self.choiceDisplayMod() pass def rangeSliderEndVolue(self, event): self.LowAndUpper[1] = event self.choiceDisplayMod() pass def viewSeedinList(self, event): if event[0] == True: print('Open eye is:', event[1]) elif event[0] == False: print('Close eye is:', event[1]) else: print('viewSeedinList error.....') pass def initAnimation(self): self.isBoardshow = False xAxis = self.groupbox.pos().x() yAxis = self.groupbox.height() self.groupBoxAnim = QPropertyAnimation(self, b'pos') self.groupBoxAnim.setDuration(200) self.groupBoxAnim.setStartValue(QPointF(xAxis, -yAxis)) # self.anim.setKeyValueAt(0.5, QPointF(0, 10)) # self.anim.setKeyValueAt(0.8, QPointF(0, 80)) self.groupBoxAnim.setEndValue(QPointF(xAxis, 0)) self.reverGroupBoxAnim = QPropertyAnimation(self, b'pos') self.reverGroupBoxAnim.setDuration(200) self.reverGroupBoxAnim.setStartValue(QPointF(xAxis, 0)) self.reverGroupBoxAnim.setEndValue(QPointF(xAxis, -yAxis)) pass def playAnimation(self): print('-----PlayAnimation-----') if self.isBoardshow == False: self.reverGroupBoxAnim.stop() self.groupBoxAnim.start() self.isBoardshow = True elif self.isBoardshow == True: self.groupBoxAnim.stop() self.reverGroupBoxAnim.start() self.isBoardshow = False pass pos = pyqtProperty(QPointF, fset=setGroup_pos) def selectLayer(self, event): self.idxSlice = self.layerScrollBar.value() self.choiceDisplayMod() pass def sliderval(self): self._low_hu = self.lowHusBar.value() self._high_hu = self.heighHusBar.value() self.choiceDisplayMod() pass def mod_Choice(self, event): if event == 'Normal': self.OperationMod = 0 elif event == 'Region': self.OperationMod = 1 self.choiceOpreationMod() pass def initDisplayfacePlane(self): if self._face == 0: self.topfaceView() elif self._face == 1: self.leftfaceView() elif self._face == 2: self.frontfaceView() pass def faceItem_Choice(self, faceEvent): if faceEvent == self.facePlane[0]: self.topfaceView() self.currentFace = self.facePlane[0] print('main view') elif faceEvent == self.facePlane[1]: self.leftfaceView() self.currentFace = self.facePlane[1] print('left view') elif faceEvent == self.facePlane[2]: self.frontfaceView() self.currentFace = self.facePlane[2] print('front view') self.choiceOpreationMod() self.getResizeEvent(self.width(), self.height()) pass #==========================MakeSureDisplayMod============================= def choiceDisplayMod(self): if self.OperationMod == 0: self.drawNomralArea() elif self.OperationMod == 1: self.drawGrowingArea() pass #========================================================================= def choiceOpreationMod(self): if self.OperationMod == 0: self.imLable.mouseMoveEvent = self.normalModMouseMoveEvent elif self.OperationMod == 1: self.imLable.mouseMoveEvent = self.regionModMouseMoveEvent self.imLable.mousePressEvent = self.regionModMousePressEvent self.imLable.mouseReleaseEvent = self.regionModMouseReleasedEvent self.imLable.wheelEvent = self.regionGrowingWheelEvent self.choiceDisplayMod() pass def topfaceView(self): self.datas = self._datas.copy() self.idxSlicelimt = self.datas.shape[0] self.faceWindowH = self.faceWindowV = self.width() tmpPalete = QPalette() tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0)) self.setPalette(tmpPalete) #=======================Init drawLayer=================== self.drawLayer = np.full(self.datas.shape, 0) print('topfaceView:', self.drawLayer.shape) pass def leftfaceView(self): self.datas = self._datas.copy() self.datas = np.rot90(self.datas, -1) self.datas = np.rot90(self.datas, axes=(0, 2)) self.idxSlicelimt = self.datas.shape[0] self.setScaleSize(max(self.datas.shape), min(self.datas.shape)) tmpPalete = QPalette() tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0)) self.setPalette(tmpPalete) #=======================Init drawLayer=================== self.drawLayer = np.full(self.datas.shape, 0) print('leftfaceView:', self.drawLayer.shape) pass def frontfaceView(self): self.datas = self._datas.copy() self.datas = np.rot90(self.datas, -1) self.idxSlicelimt = self.datas.shape[0] width = self.datas.shape[0] height = self.datas.shape[1] depth = self.datas.shape[2] self.setScaleSize(max(width, height, depth), min(width, height, depth)) tmpPalete = QPalette() tmpPalete.setColor(QPalette.Background, QColor(0, 0, 0)) self.setPalette(tmpPalete) #=======================Init drawLayer=================== self.drawLayer = np.full(self.datas.shape, 0) print('frontfaceView:', self.drawLayer.shape) pass def drawNomralArea(self): self.idxSlice = np.clip(self.idxSlice, 0, self.idxSlicelimt -1) self.imData = self.datas[self.idxSlice] self.displayDicomImage() pass def drawGrowingArea(self): self.imgOriginal = SimpleITK.GetImageFromArray(self.datas[self.idxSlice]) self.imgWhiteMatter = SimpleITK.ConnectedThreshold(image1=self.imgOriginal, seedList=self.seedList, lower=self.LowAndUpper[0], upper=self.LowAndUpper[1], replaceValue=1, ) self.regionArea = SimpleITK.GetArrayFromImage(self.imgWhiteMatter) #================if use draw or eraser==================== if np.sum(self.drawLayer[self.idxSlice] != 0) != 0: self.regionDrawLayerCombinEvent() self.drawGrowingAreaContour() pass def drawGrowingAreaContour(self): foreColorvalue = 1 self.imgWhiteMatter = SimpleITK.GetImageFromArray(self.regionArea) self.imgWhiteMatterNoHoles = SimpleITK.VotingBinaryHoleFilling(image1=self.imgWhiteMatter, radius=[2] * 3, majorityThreshold=50, backgroundValue=0, foregroundValue=foreColorvalue) regionContour = SimpleITK.LabelContour(self.imgWhiteMatterNoHoles) # tmpWmatter = self.imgWhiteMatter # regionContour = tmpWmatter | regionContour tmpImage = SimpleITK.LabelOverlay(self.imgOriginal, regionContour) regionContourArray = SimpleITK.GetArrayFromImage(tmpImage) self.imData = regionContourArray self.displayDicomImage() pass #==============================Key board event ============================================ def customComboxKeyEvent(self, event): print('ComboxKeyEvent') pass def useforTestKeyEvent(self): print('just test combobox key event') # self.displayDicomImage() pass #==============================Use for display dicom image================================= def displayDicomImage(self): if self.imData is not None: raw_data = self.imData shape = self.imData.shape # maxNum = max(shape) # minNum = min(shape) raw_data[raw_data < 0] = 0 raw_data[raw_data > 255] = 255 if len(shape) >= 3: data = raw_data #=================用于调节对比度的方法======================= # data = (raw_data - self._low_hu) / self.window_width * 256 # print('---------Update3d--------') #=========================================================== data = data.astype(np.int8) tmpImage = QImage(data, shape[1], shape[0], shape[1] * shape[2], QImage.Format_RGB888) pixmap = QPixmap.fromImage(tmpImage) # pixmap = pixmap.scaled(self.faceWindowH , self.faceWindowV ) # pixmap = pixmap.scaled(self.xSpacing, self.zSpacing) # pixmap = pixmap.scaled(1024, 128) self.imLable.setPixmap(pixmap) elif len(shape) < 3: data = raw_data # data = (raw_data - self._low_hu) / self.window_width * 256 # print('---------Update2d---------') data = data.astype(np.int8) tmpImage = QImage(data, shape[1], shape[0], QImage.Format_Grayscale8) tmpImage.setColorTable(self._color_table) pixmap = QPixmap.fromImage(tmpImage) # pixmap = pixmap.scaled(self.faceWindowH, self.faceWindowV) # pixmap = pixmap.scaled(self.xSpacing, self.zSpacing) # pixmap = pixmap.scaled(1024, 128) self.imLable.setPixmap(pixmap) pass def normalModMouseMoveEvent(self, event): if event.buttons() == Qt.LeftButton: xAxis = event.pos().x() yAxis = event.pos().y() self.choiceDisplayMod() pass #=============================Region draw layer operation========================================== def regionDrawLayerEvent(self, x, y, value): self.regionArea[y - self.regionDrawSize:y + self.regionDrawSize, x - self.regionDrawSize:x + self.regionDrawSize] = value self.drawLayer[self.idxSlice] = self.regionArea pass def regionDrawLayerCombinEvent(self): self.regionArea = self.drawLayer[self.idxSlice].astype(np.uint8) pass #=============================Region mod mouse Press and released event============================ def regionModMousePressEvent(self, event): if event.buttons() == Qt.LeftButton and self.regionDrawMod != 0: xAxis = event.pos().x() yAxis = event.pos().y() if xAxis >= 0 and yAxis >= 0: tmpX = math.floor(xAxis * (self.baseImageSize / self.imLable.width())) tmpY = math.floor(yAxis * (self.baseImageSize / self.imLable.height())) if self.regionDrawMod == 1: self.regionDrawLayerEvent(tmpX, tmpY, 1) elif self.regionDrawMod == 2: self.regionDrawLayerEvent(tmpX, tmpY, 0) self.drawGrowingAreaContour() pass def regionModMouseReleasedEvent(self, Event): if Event.buttons() == Qt.RightButton: print('Right button released') pass #================================================================================================== #=====================================Region mod mouse move event================================== def regionModMouseMoveEvent(self, event): self.posX = event.pos().x() self.posY = event.pos().y() if event.buttons() == Qt.LeftButton and self.regionDrawMod == 0: if self.regionDrawMod == 0: xAxis = event.pos().x() yAxis = event.pos().y() if xAxis >= 0 and yAxis >= 0: self.PosXY[0] = math.floor(xAxis * (self.baseImageSize / self.imLable.width())) self.PosXY[1] = math.floor(yAxis * (self.baseImageSize / self.imLable.height())) self.seedList[self.seedSelectNum] = (self.PosXY[0], self.PosXY[1]) else: print('Region Mod has Nagtive number') elif event.buttons() == Qt.LeftButton and self.regionDrawMod != 0: xAxis = event.pos().x() yAxis = event.pos().y() if xAxis >= 0 and yAxis >= 0: tmpX = math.floor(xAxis * (self.baseImageSize / self.imLable.width())) tmpY = math.floor(yAxis * (self.baseImageSize / self.imLable.height())) if self.regionDrawMod == 1: self.regionDrawLayerEvent(tmpX, tmpY, 1) elif self.regionDrawMod == 2: self.regionDrawLayerEvent(tmpX, tmpY, 0) else: print('regionModMouseMoveEvent regionDrawMod error......') return self.drawGrowingAreaContour() return else: print('regionModMouseMoveEvent error......') self.choiceDisplayMod() pass #=================================SetWindowSizeEvent========================================== def setScaleSize(self, maxnum, minnum): self.faceWindowH = maxnum self.faceWindowV = minnum * (max(self.xSpacing, self.ySpacing, self.zSpacing) / min(self.xSpacing, self.ySpacing, self.zSpacing)) pass def getResizeEvent(self, sizeX, sizeY): if self.currentFace == self.facePlane[0]: tmpSize = min(sizeX, sizeY) self.imLable.resize(tmpSize, tmpSize) elif self.currentFace == self.facePlane[1]: #==================Resize Lable=================== self.setScaleSize(min(sizeX, sizeY), min(sizeX, sizeY) * (min(self.datas.shape)/max(self.datas.shape))) self.imLable.resize(self.faceWindowH, self.faceWindowV) elif self.currentFace == self.facePlane[2]: self.setScaleSize(min(sizeX, sizeY), min(sizeX, sizeY) * (min(self.datas.shape) / max(self.datas.shape))) self.imLable.resize(self.faceWindowH, self.faceWindowV) #==================Move Lable===================== maxPosY = max(sizeY, self.imLable.height()) minPoxY = min(sizeY, self.imLable.height()) tmpPosX = np.clip((sizeX - sizeY), 0, max(sizeX, sizeY)) / 2 tmpPosY = (maxPosY - minPoxY) / 2 self.imLable.move(tmpPosX, tmpPosY) pass #===========================mousewheelEvent================================== def regionGrowingWheelEvent(self, event): angle = event.angleDelta() / 8 angleX = angle.x() angleY = angle.y() if angleY > 0: self.regionDrawSize -= 1 elif angleY < 0: self.regionDrawSize += 1 pass #==========================RegionDrawMod===================== def setRegionDrawMod(self, event): if event == 0: self.regionDrawMod = 0 elif event == 1: self.regionDrawMod = 1 elif event == 2: self.regionDrawMod = 2 else: print('setRegionDrawMod error....') pass #====================Use for paint or eraser==================== def paintEvent(self, QPaintEvent): pen1 = QPen(Qt.blue, 1) q = QPainter(self) q.setPen(pen1) q.drawRect(self.posX - 25, self.posY - 25, 50, 50) # print('paintEvent') pass @property def window_width(self): return self._high_hu - self._low_hu #======================================================================================================================= # pathDicom = "D:/Dicomfile/MT_07/" # idxSlice = 50 # reader = SimpleITK.ImageSeriesReader() # filenamesDICOM = reader.GetGDCMSeriesFileNames(pathDicom) # # reader.SetFileNames(filenamesDICOM) # imgOriginals = reader.Execute() # datas = SimpleITK.GetArrayFromImage(imgOriginals) # Spacing = imgOriginals.GetSpacing() # # if __name__ == '__main__': # app = QApplication(sys.argv) # win = dicomImage2DdisplayWidget(face=0, datas= datas, spacing=Spacing) # win.show() # sys.exit(app.exec_())
def bind(source: QScrollBar, target: QScrollBar) -> None: # bind target scroll bar to `source` (range and value). target.setRange(source.minimum(), source.maximum()) target.setValue(source.value()) source.rangeChanged.connect(target.setRange) source.valueChanged.connect(target.setValue)
class _s_CentralWidget(QWidget): ############################################################################### # CentralWidget SIGNALS ############################################################################### """ splitterCentralRotated() """ splitterCentralRotated = pyqtSignal() ############################################################################### def __init__(self, parent=None): super(_s_CentralWidget, self).__init__(parent) self.parent = parent #This variables are used to save the splitter sizes before hide self._splitterMainSizes = None self._splitterAreaSizes = None self.lateralPanel = None hbox = QHBoxLayout(self) hbox.setContentsMargins(0, 0, 0, 0) hbox.setSpacing(0) #Create Splitters to divide the UI in: MainPanel, Explorer, Misc self._splitterArea = QSplitter(Qt.Horizontal) self._splitterMain = QSplitter(Qt.Vertical) #Create scrollbar for follow mode self.scrollBar = QScrollBar(Qt.Vertical, self) self.scrollBar.setFixedWidth(20) self.scrollBar.setToolTip('Follow Mode: Scroll the Editors together') self.scrollBar.hide() self.scrollBar.valueChanged[int].connect(self.move_follow_scrolls) #Add to Main Layout hbox.addWidget(self.scrollBar) hbox.addWidget(self._splitterArea) def insert_central_container(self, container): self.mainContainer = container self._splitterMain.insertWidget(0, container) def insert_lateral_container(self, container): self.lateralPanel = LateralPanel(container) self._splitterArea.insertWidget(0, self.lateralPanel) def insert_bottom_container(self, container): self.misc = container self._splitterMain.insertWidget(1, container) def showEvent(self, event): #Show Event QWidget.showEvent(self, event) #Avoid recalculate the panel sizes if they are already loaded if self._splitterArea.count() == 2: return #Rearrange widgets on Window self._splitterArea.insertWidget(0, self._splitterMain) if not event.spontaneous(): self.change_misc_visibility() if bin(settings.UI_LAYOUT)[-1] == '1': self.splitter_central_rotate() if bin(settings.UI_LAYOUT >> 1)[-1] == '1': self.splitter_misc_rotate() if bin(settings.UI_LAYOUT >> 2)[-1] == '1': self.splitter_central_orientation() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) #Lists of sizes as list of QVariant- heightList = [QVariant, QVariant] heightList = list(qsettings.value("window/central/mainSize", [(self.height() / 3) * 2, self.height() / 3])) widthList = list(qsettings.value("window/central/areaSize", [(self.width() / 6) * 5, self.width() / 6])) self._splitterMainSizes = [int(heightList[0]), int(heightList[1])] self._splitterAreaSizes = [int(widthList[0]), int(widthList[1])] #Set the sizes to splitters #self._splitterMain.setSizes(self._splitterMainSizes) self._splitterMain.setSizes(self._splitterMainSizes) self._splitterArea.setSizes(self._splitterAreaSizes) self.misc.setVisible( qsettings.value("window/show_misc", False, type=bool)) def change_misc_visibility(self, on_start=False): if self.misc.isVisible(): self._splitterMainSizes = self._splitterMain.sizes() self.misc.hide() widget = self.mainContainer.get_actual_widget() if widget: widget.setFocus() else: self.misc.show() self.misc.gain_focus() def change_main_visibility(self): if self.mainContainer.isVisible(): self.mainContainer.hide() else: self.mainContainer.show() def change_explorer_visibility(self, force_hide=False): if self.lateralPanel.isVisible() or force_hide: self._splitterAreaSizes = self._splitterArea.sizes() self.lateralPanel.hide() else: self.lateralPanel.show() def splitter_central_rotate(self): w1, w2 = self._splitterArea.widget(0), self._splitterArea.widget(1) self._splitterArea.insertWidget(0, w2) self._splitterArea.insertWidget(1, w1) self.splitterCentralRotated.emit() def splitter_central_orientation(self): if self._splitterArea.orientation() == Qt.Horizontal: self._splitterArea.setOrientation(Qt.Vertical) else: self._splitterArea.setOrientation(Qt.Horizontal) def splitter_misc_rotate(self): w1, w2 = self._splitterMain.widget(0), self._splitterMain.widget(1) self._splitterMain.insertWidget(0, w2) self._splitterMain.insertWidget(1, w1) def splitter_misc_orientation(self): if self._splitterMain.orientation() == Qt.Horizontal: self._splitterMain.setOrientation(Qt.Vertical) else: self._splitterMain.setOrientation(Qt.Horizontal) def get_area_sizes(self): if self.lateralPanel.isVisible(): self._splitterAreaSizes = self._splitterArea.sizes() return self._splitterAreaSizes def get_main_sizes(self): if self.misc.isVisible(): self._splitterMainSizes = self._splitterMain.sizes() return self._splitterMainSizes def enable_follow_mode_scrollbar(self, val): if val: editorWidget = self.mainContainer.get_actual_editor() maxScroll = editorWidget.verticalScrollBar().maximum() position = editorWidget.verticalScrollBar().value() self.scrollBar.setMaximum(maxScroll) self.scrollBar.setValue(position) self.scrollBar.setVisible(val) def move_follow_scrolls(self, val): widget = self.mainContainer._tabMain.currentWidget() diff = widget._sidebarWidget.highest_line - val s1 = self.mainContainer._tabMain.currentWidget().verticalScrollBar() s2 = self.mainContainer._tabSecondary.\ currentWidget().verticalScrollBar() s1.setValue(val) s2.setValue(val + diff)
class BitsWidget(QWidget): def __init__(self, offset, bit_size, row_width, grid_width, grid_height, bit_border_threshold) -> None: super().__init__() self._app = App() self._offset = offset self._bit_size = bit_size self._row_width = row_width self._grid_width = grid_width self._grid_h_offset = 0 self._grid_height = grid_height self._grid_v_offset = 0 self._one_color = Qt.blue self._zero_color = Qt.white self._color_table = [ QColor(self._zero_color).rgb(), QColor(self._one_color).rgb(), ] self._bit_border_threshold = bit_border_threshold self._easter_egg = 0 self._painting = False self._bits_area = QWidget() self._h_scrollbar = QScrollBar(orientation=Qt.Horizontal) self._h_scrollbar.setMinimum(0) self._h_scrollbar.valueChanged.connect(self._on_scrollbar_change) self._h_scrollbar.hide() self._v_scrollbar = QScrollBar(orientation=Qt.Vertical) self._v_scrollbar.setMinimum(0) self._v_scrollbar.valueChanged.connect(self._on_scrollbar_change) self._v_scrollbar.hide() inner_layout = QVBoxLayout() inner_layout.setContentsMargins(0, 0, 0, 0) inner_layout.setSpacing(0) inner_layout.addWidget(self._bits_area, stretch=1) inner_layout.addWidget(self._h_scrollbar) inner_widget = QWidget() inner_widget.setLayout(inner_layout) outer_layout = QHBoxLayout() outer_layout.setContentsMargins(0, 0, 0, 0) outer_layout.setSpacing(0) outer_layout.addWidget(inner_widget, stretch=1) outer_layout.addWidget(self._v_scrollbar) self.setLayout(outer_layout) @property def offset(self) -> int: return self._offset @offset.setter def offset(self, new_offset): self._offset = new_offset @property def bit_size(self) -> int: return self._bit_size @bit_size.setter def bit_size(self, size: int): self._bit_size = size @property def row_width(self) -> int: return self._row_width @row_width.setter def row_width(self, width: int): self._row_width = width @property def grid_width(self) -> int: return self._grid_width @grid_width.setter def grid_width(self, size: int): self._grid_width = size @property def grid_h_offset(self) -> int: return self._grid_h_offset @grid_h_offset.setter def grid_h_offset(self, offset: int): self._grid_h_offset = offset @property def grid_height(self) -> int: return self._grid_height @grid_height.setter def grid_height(self, size: int): self._grid_height = size @property def grid_v_offset(self) -> int: return self._grid_v_offset @grid_v_offset.setter def grid_v_offset(self, offset: int): self._grid_v_offset = offset @property def _bits_area_width(self): return self._bits_area.width() @property def _bits_area_height(self): return self._bits_area.height() @property def _num_rows(self): return ceil((self._app.num_bits - self._offset) / self._row_width) def set_bit_border_threshold(self, threshold): self._bit_border_threshold = threshold def load_file(self, filename, max_bytes): self._app.load_file(filename, max_bytes) def paintEvent(self, a0: QPaintEvent) -> None: super().paintEvent(a0) if not self._app.num_bits: return self._painting = True self._set_scrollbars() self._paint_bits() self._draw_grid() self._painting = False def _paint_bits(self): visible_columns = self._bits_area_width // self._bit_size visible_rows = self._bits_area_height // self._bit_size bitmap = self._app.create_bitmap( self._offset, self._row_width, self._h_scrollbar.value(), self._v_scrollbar.value(), visible_rows, visible_columns, ) pixmap = self._create_pixmap(bitmap.data, bitmap.width, bitmap.bytes_per_row) painter = QPainter(self) painter.drawPixmap(0, 0, pixmap) self._draw_bit_separators(painter, pixmap.width(), pixmap.height()) self._draw_last_row_of_bits(painter, bitmap.remainder, pixmap) painter.end() def _draw_bit_separators(self, painter: QPainter, right, bottom): if self._bit_size <= self._bit_border_threshold: return painter.setPen(QPen(Qt.black, 1)) self._draw_h_grid(painter, right, bottom, 1, 0) self._draw_v_grid(painter, right, bottom, 1, 0) def _draw_last_row_of_bits(self, painter, last_row_of_bits, pixmap): painter.setPen( QPen( Qt.black if self._bit_size > self._bit_border_threshold else Qt.transparent, 1, Qt.SolidLine, )) for i, b in enumerate(last_row_of_bits): self._draw_bit(painter, i, pixmap.height() // self._bit_size, b) def _draw_bit(self, painter: QPainter, x, y, bit): painter.setBrush( QBrush(self._one_color if bit else self._zero_color, Qt.SolidPattern)) painter.drawRect(x * self._bit_size, y * self._bit_size, self._bit_size, self._bit_size) def _draw_grid(self): if not self._grid_width and not self._grid_height: return if not self._num_rows: return painter = QPainter(self) painter.setPen(QPen(Qt.red, 1, Qt.SolidLine)) right = min( (self._row_width - self._h_scrollbar.value()) * self._bit_size, self._bits_area_width, ) bottom = min( (self._num_rows - self._v_scrollbar.value()) * self._bit_size, self._bits_area_height, ) self._draw_h_grid( painter, right, bottom, self._grid_width, self._grid_h_offset - self._h_scrollbar.value(), ) self._draw_v_grid( painter, right, bottom, self._grid_height, self._grid_v_offset - self._v_scrollbar.value(), ) def _create_pixmap(self, data: bytes, width, bytes_per_row: int): height = len(data) // bytes_per_row image = QImage(data, width, height, bytes_per_row, QImage.Format_Mono) image.setColorTable(self._color_table) return QPixmap.fromImage(image).scaled(width * self._bit_size, height * self._bit_size) def _draw_h_grid(self, painter, right, bottom, grid_width, grid_offset): if not grid_width: return start_offset = grid_offset % grid_width start = start_offset * self._bit_size for x in range(start, right + 1, grid_width * self._bit_size): painter.drawLine(x, 0, x, bottom) def _draw_v_grid(self, painter, right, bottom, grid_height, grid_offset): if not grid_height: return start_offset = grid_offset % grid_height start = start_offset * self._bit_size for y in range(start, bottom + 1, grid_height * self._bit_size): painter.drawLine(0, y, right, y) def _set_scrollbars(self): self._set_h_scrollbar() v_visibility_changed = self._set_v_scrollbar() if v_visibility_changed: h_visibility_changed = self._set_h_scrollbar() if h_visibility_changed: self._set_v_scrollbar() def _set_h_scrollbar(self): h_scroll_max = self._calc_h_scrollbar_max() was_visible = self._h_scrollbar.isVisible() if h_scroll_max > 0: self._h_scrollbar.setMaximum(h_scroll_max) self._h_scrollbar.show() return not was_visible else: self._h_scrollbar.setValue(0) self._h_scrollbar.hide() return was_visible def _set_v_scrollbar(self): v_scroll_max = self._calc_v_scrollbar_max() was_visible = self._v_scrollbar.isVisible() if v_scroll_max > 0: self._v_scrollbar.setMaximum(v_scroll_max) self._v_scrollbar.show() return not was_visible else: self._v_scrollbar.setValue(0) self._v_scrollbar.hide() return was_visible def _calc_h_scrollbar_max(self): return self._row_width - (self._bits_area_width // self.bit_size) def _calc_v_scrollbar_max(self): visible_rows = self._bits_area_height // self.bit_size return self._num_rows - visible_rows def wheelEvent(self, event: QWheelEvent) -> None: y_delta = event.angleDelta().y() if y_delta: notches = ceil(y_delta / 120) self._v_scrollbar.setValue(self._v_scrollbar.value() - notches) x_delta = event.angleDelta().x() if x_delta: notches = ceil(x_delta / 120) self._h_scrollbar.setValue(self._h_scrollbar.value() - notches) def mousePressEvent(self, a0: QMouseEvent) -> None: if (a0.x() <= self._bit_size and a0.y() <= self._bit_size and self._easter_egg < 9): self._easter_egg += 1 elif (self._bit_size <= a0.x() <= self._bit_size * 2 and self._bit_size <= a0.y() <= self._bit_size * 2 and 9 <= self._easter_egg < 12): self._easter_egg += 1 elif (self._bit_size * 2 <= a0.x() <= self._bit_size * 3 and self._bit_size * 2 <= a0.y() <= self._bit_size * 3 and self._easter_egg == 12): tmp = self._one_color self._one_color = self._zero_color self._zero_color = tmp self._color_table = [self._color_table[1], self._color_table[0]] self._easter_egg = 0 else: self._easter_egg = 0 def _on_scrollbar_change(self): if not self._painting: self.repaint()
def adjustScrollBar(self, scrollBar: QScrollBar, factor: float): scrollBar.setValue( int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2)))
class ScrollBar(QWidget): """ 定义一个可以变换样式的滚动条 """ def __init__(self, externalScrollBar=None, parent=None): super().__init__(parent) self.externalScrollBar = externalScrollBar # 实例化两个滚动条 self.minScrollBar = QScrollBar(Qt.Vertical, self) self.maxScrollBar = QScrollBar(Qt.Vertical, self) # 实例化一个控制滚动条显示的计时器 self.timer = QTimer(self) # 初始化 self.initWidget() self.associateScrollBar() self.setQss() def initWidget(self): """ 初始化小部件 """ self.setFixedWidth(20) self.minScrollBar.move(15, 0) self.maxScrollBar.hide() self.timer.setInterval(2000) self.timer.timeout.connect(self.showMinScrollBar) self.setAttribute(Qt.WA_TranslucentBackground) # 分配ID self.setObjectName('father') self.minScrollBar.setObjectName('minScrollBar') self.maxScrollBar.setObjectName('maxScrollBar') def adjustSrollBarHeight(self): """ 根据父级窗口的高度调整滚动条高度 """ if self.parent(): self.minScrollBar.setFixedHeight(self.parent().height() - 153) self.maxScrollBar.setFixedHeight(self.parent().height() - 153) def enterEvent(self, e: QEnterEvent): """ 鼠标进入界面时显示大滚动条并停止秒表 """ self.maxScrollBar.show() self.minScrollBar.hide() self.timer.stop() def leaveEvent(self, e): """ 鼠标离开打开秒表 """ self.timer.start() def showMinScrollBar(self): """ 定时溢出时隐藏大滚动条 """ self.timer.stop() self.maxScrollBar.hide() self.minScrollBar.show() def setQss(self): """ 设置层叠样式 """ with open(r'resource\css\my_scrollBar.qss', encoding='utf-8') as f: self.setStyleSheet(f.read()) def associateScrollBar(self): """ 关联滚动条 """ if self.externalScrollBar: # 设置最大值 self.minScrollBar.setMaximum(self.externalScrollBar.maximum()) self.maxScrollBar.setMaximum(self.externalScrollBar.maximum()) # 关联滚动条 self.externalScrollBar.valueChanged.connect( lambda: self.minScrollBar.setValue(self.externalScrollBar. value())) self.minScrollBar.valueChanged.connect(self.__minScrollBarChanged) self.maxScrollBar.valueChanged.connect( lambda: self.minScrollBar.setValue(self.maxScrollBar.value())) def __minScrollBarChanged(self): """ minScrollBar改变时同时改变另外两个滚动条的值 """ self.maxScrollBar.setValue(self.minScrollBar.value()) self.externalScrollBar.setValue(self.minScrollBar.value())
def reset_scrollbar(self, scrollbar_preview: QScrollBar): scrollbar_preview.setValue(self.sprite_preview_model.selected_sprite) if self.sprite_preview_model.sprites is not None: scrollbar_preview.setMaximum( len(self.sprite_preview_model.sprites) - 1)
def setupTab2(self, tab2): """Special widgets for preview panel""" scrollContainer = QVBoxLayout() scrollArea = QScrollArea() scrollArea.setWidgetResizable(True) mainWidget = QWidget() layout = QVBoxLayout() mainWidget.setLayout(layout) mainWidget.setMinimumSize(QSize(420, 800)) scrollArea.setWidget(mainWidget) scrollContainer.addWidget(scrollArea) tab2.setLayout(scrollContainer) # Dialog group0 = QGroupBox("Dialog") group1Layout = QVBoxLayout() layoutRow1 = QHBoxLayout() layoutRow2 = QHBoxLayout() group1Layout.addLayout(layoutRow1) group1Layout.addLayout(layoutRow2) group0.setLayout(group1Layout) layout.addWidget(group0) b1 = QPushButton(self.tr("Info")) b1.clicked.connect(lambda: QMessageBox.information( self, "Info", self.tr("This is a message."), QMessageBox.Ok, QMessageBox.Ok)) b2 = QPushButton(self.tr("Question")) b2.clicked.connect(lambda: QMessageBox.question( self, "question", self.tr("Are you sure?"), QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes)) b3 = QPushButton(self.tr("Warning")) b3.clicked.connect(lambda: QMessageBox.warning( self, "warning", self.tr("This is a warning."), QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes)) b4 = QPushButton(self.tr("Error")) b4.clicked.connect(lambda: QMessageBox.critical( self, "error", self.tr("It's a error."), QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes)) b5 = QPushButton(self.tr("About")) b5.clicked.connect(lambda: QMessageBox.about( self, "about", self.tr("About this software"))) b6 = QPushButton(self.tr("Input")) # ,"输入对话框")) b6.clicked.connect(lambda: QInputDialog.getInt( self, self.tr("input"), self.tr("please input int"))) b6.clicked.connect(lambda: QInputDialog.getDouble( self, self.tr("input"), self.tr("please input float"))) b6.clicked.connect(lambda: QInputDialog.getItem( self, self.tr("input"), self.tr("please select"), ["aaa", "bbb"])) b7 = QPushButton(self.tr("Color")) # ,"颜色对话框")) b7.clicked.connect(lambda: QColorDialog.getColor()) b8 = QPushButton(self.tr("Font")) # ,"字体对话框")) b8.clicked.connect(lambda: QFontDialog.getFont()) b9 = QPushButton(self.tr("OpenFile")) # ,"打开对话框")) b9.clicked.connect(lambda: QFileDialog.getOpenFileName( self, "open", "", "Text(*.txt *.text)")) b10 = QPushButton(self.tr("SaveFile")) # ,"保存对话框")) b10.clicked.connect(lambda: QFileDialog.getSaveFileName()) layoutRow1.addWidget(b1) layoutRow1.addWidget(b2) layoutRow1.addWidget(b3) layoutRow1.addWidget(b4) layoutRow1.addWidget(b5) layoutRow2.addWidget(b6) layoutRow2.addWidget(b7) layoutRow2.addWidget(b8) layoutRow2.addWidget(b9) layoutRow2.addWidget(b10) # DateTime group1 = QGroupBox("DateTime") group1.setCheckable(True) group1Layout = QHBoxLayout() layoutRow1 = QVBoxLayout() layoutRow2 = QVBoxLayout() group1Layout.addLayout(layoutRow1) group1Layout.addLayout(layoutRow2) group1.setLayout(group1Layout) layout.addWidget(group1) group1.setMaximumHeight(240) dt1 = QDateEdit() dt1.setDate(QDate.currentDate()) dt2 = QTimeEdit() dt2.setTime(QTime.currentTime()) dt3 = QDateTimeEdit() dt3.setDateTime(QDateTime.currentDateTime()) dt4 = QDateTimeEdit() dt4.setCalendarPopup(True) dt5 = QCalendarWidget() dt5.setMaximumSize(QSize(250, 240)) layoutRow1.addWidget(dt1) layoutRow1.addWidget(dt2) layoutRow1.addWidget(dt3) layoutRow1.addWidget(dt4) layoutRow2.addWidget(dt5) # Slider group2 = QGroupBox("Sliders") group2.setCheckable(True) group2Layout = QVBoxLayout() layoutRow1 = QHBoxLayout() layoutRow2 = QHBoxLayout() group2Layout.addLayout(layoutRow1) group2Layout.addLayout(layoutRow2) group2.setLayout(group2Layout) layout.addWidget(group2) slider = QSlider() slider.setOrientation(Qt.Horizontal) slider.setMaximum(100) progress = QProgressBar() slider.valueChanged.connect(progress.setValue) slider.setValue(50) scroll1 = QScrollBar() scroll2 = QScrollBar() scroll3 = QScrollBar() scroll1.setMaximum(255) scroll2.setMaximum(255) scroll3.setMaximum(255) scroll1.setOrientation(Qt.Horizontal) scroll2.setOrientation(Qt.Horizontal) scroll3.setOrientation(Qt.Horizontal) c = QLabel(self.tr("Slide to change color")) # , "拖动滑块改变颜色")) c.setAutoFillBackground(True) c.setAlignment(Qt.AlignCenter) # c.setStyleSheet("border:1px solid gray;") c.setStyleSheet("background:rgba(0,0,0,100);") def clr(): # clr=QColor(scroll1.getValue(),scroll2.getValue(),scroll3.getValue(),100) # p=QPalette() # p.setColor(QPalette.Background,clr) # c.setPalette(p) c.setStyleSheet("background: rgba({},{},{},100);".format( scroll1.value(), scroll2.value(), scroll3.value())) scroll1.valueChanged.connect(clr) scroll2.valueChanged.connect(clr) scroll3.valueChanged.connect(clr) scroll1.setValue(128) layoutRow1.addWidget(slider) layoutRow1.addWidget(progress) layCol1 = QVBoxLayout() layCol1.addWidget(scroll1) layCol1.addWidget(scroll2) layCol1.addWidget(scroll3) layoutRow2.addLayout(layCol1) layoutRow2.addWidget(c) # Meter group3 = QGroupBox("Meters") group3.setCheckable(True) layRow = QHBoxLayout() group3.setLayout(layRow) layout.addWidget(group3) dial1 = QDial() dial2 = QDial() dial2.setNotchesVisible(True) dial1.valueChanged.connect(dial2.setValue) layRow.addWidget(dial1) layRow.addWidget(dial2) layout.addStretch(1)
class CarlaRackW(QFrame, HostWidgetMeta): #class CarlaRackW(QFrame, HostWidgetMeta, metaclass=PyQtMetaClass): def __init__(self, parent, host, doSetup = True): QFrame.__init__(self, parent) self.host = host if False: # kdevelop likes this :) host = CarlaHostMeta() self.host = host # ------------------------------------------------------------- self.fLayout = QHBoxLayout(self) self.fLayout.setContentsMargins(0, 0, 0, 0) self.fLayout.setSpacing(0) self.setLayout(self.fLayout) self.fPadLeft = QLabel(self) self.fPadLeft.setFixedWidth(25) self.fPadLeft.setObjectName("PadLeft") self.fPadLeft.setText("") self.fPadRight = QLabel(self) self.fPadRight.setFixedWidth(25) self.fPadRight.setObjectName("PadRight") self.fPadRight.setText("") self.fRack = CarlaRackList(self, host) self.fRack.setObjectName("CarlaRackList") self.fRack.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.fRack.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.fRack.currentRowChanged.connect(self.slot_currentRowChanged) sb = self.fRack.verticalScrollBar() self.fScrollBar = QScrollBar(Qt.Vertical, self) self.fScrollBar.setMinimum(sb.minimum()) self.fScrollBar.setMaximum(sb.maximum()) self.fScrollBar.setValue(sb.value()) #sb.actionTriggered.connect(self.fScrollBar.triggerAction) #sb.sliderMoved.connect(self.fScrollBar.) #sb.sliderPressed.connect(self.fScrollBar.) #sb.sliderReleased.connect(self.fScrollBar.) sb.rangeChanged.connect(self.fScrollBar.setRange) sb.valueChanged.connect(self.fScrollBar.setValue) self.fScrollBar.rangeChanged.connect(sb.setRange) self.fScrollBar.valueChanged.connect(sb.setValue) self.fLayout.addWidget(self.fPadLeft) self.fLayout.addWidget(self.fRack) self.fLayout.addWidget(self.fPadRight) self.fLayout.addWidget(self.fScrollBar) # ------------------------------------------------------------- # Internal stuff self.fParent = parent self.fPluginCount = 0 self.fPluginList = [] self.fCurrentRow = -1 self.fLastSelectedItem = None # ------------------------------------------------------------- # Set-up GUI stuff #app = QApplication.instance() #pal1 = app.palette().base().color() #pal2 = app.palette().button().color() #col1 = "stop:0 rgb(%i, %i, %i)" % (pal1.red(), pal1.green(), pal1.blue()) #col2 = "stop:1 rgb(%i, %i, %i)" % (pal2.red(), pal2.green(), pal2.blue()) self.setStyleSheet(""" QLabel#PadLeft { background-image: url(:/bitmaps/rack_padding_left.png); background-repeat: repeat-y; } QLabel#PadRight { background-image: url(:/bitmaps/rack_padding_right.png); background-repeat: repeat-y; } CarlaRackList#CarlaRackList { background-color: black; } """) # ------------------------------------------------------------- # Connect actions to functions host.PluginAddedCallback.connect(self.slot_handlePluginAddedCallback) host.PluginRemovedCallback.connect(self.slot_handlePluginRemovedCallback) host.ReloadAllCallback.connect(self.slot_handleReloadAllCallback) if not doSetup: return parent.ui.menu_Canvas.hide() parent.ui.act_plugins_enable.triggered.connect(self.slot_pluginsEnable) parent.ui.act_plugins_disable.triggered.connect(self.slot_pluginsDisable) parent.ui.act_plugins_volume100.triggered.connect(self.slot_pluginsVolume100) parent.ui.act_plugins_mute.triggered.connect(self.slot_pluginsMute) parent.ui.act_plugins_wet100.triggered.connect(self.slot_pluginsWet100) parent.ui.act_plugins_bypass.triggered.connect(self.slot_pluginsBypass) parent.ui.act_plugins_center.triggered.connect(self.slot_pluginsCenter) parent.ui.act_plugins_panic.triggered.connect(self.slot_pluginsDisable) parent.ui.act_settings_configure.triggered.connect(self.slot_configureCarla) # ----------------------------------------------------------------- @pyqtSlot(int, str) def slot_handlePluginAddedCallback(self, pluginId, pluginName): pitem = CarlaRackItem(self.fRack, pluginId, self.fParent.getSavedSettings()[CARLA_KEY_MAIN_USE_CUSTOM_SKINS]) self.fPluginList.append(pitem) self.fPluginCount += 1 if not self.fParent.isProjectLoading(): pitem.getWidget().setActive(True, True, True) @pyqtSlot(int) def slot_handlePluginRemovedCallback(self, pluginId): pitem = self.getPluginItem(pluginId) self.fPluginCount -= 1 self.fPluginList.pop(pluginId) self.fRack.takeItem(pluginId) if pitem is not None: pitem.closeEditDialog() del pitem # push all plugins 1 slot back for i in range(pluginId, self.fPluginCount): pitem = self.fPluginList[i] pitem.setPluginId(i) # ----------------------------------------------------------------- # HostWidgetMeta methods def removeAllPlugins(self): while self.fRack.takeItem(0): pass for pitem in self.fPluginList: if pitem is None: break pitem.closeEditDialog() del pitem self.fPluginCount = 0 self.fPluginList = [] def engineStarted(self): pass def engineStopped(self): pass def idleFast(self): for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().idleFast() def idleSlow(self): for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().idleSlow() def projectLoadingStarted(self): self.fRack.setEnabled(False) def projectLoadingFinished(self): self.fRack.setEnabled(True) def saveSettings(self, settings): pass def showEditDialog(self, pluginId): dialog = self.getPluginEditDialog(pluginId) if dialog is None: return dialog.show() # ----------------------------------------------------------------- @pyqtSlot() def slot_pluginsEnable(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setActive(True, True, True) @pyqtSlot() def slot_pluginsDisable(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setActive(False, True, True) @pyqtSlot() def slot_pluginsVolume100(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 1.0) @pyqtSlot() def slot_pluginsMute(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setInternalParameter(PLUGIN_CAN_VOLUME, 0.0) @pyqtSlot() def slot_pluginsWet100(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 1.0) @pyqtSlot() def slot_pluginsBypass(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setInternalParameter(PLUGIN_CAN_DRYWET, 0.0) @pyqtSlot() def slot_pluginsCenter(self): if not self.host.is_engine_running(): return for pitem in self.fPluginList: if pitem is None: break pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_LEFT, -1.0) pitem.getWidget().setInternalParameter(PARAMETER_BALANCE_RIGHT, 1.0) pitem.getWidget().setInternalParameter(PARAMETER_PANNING, 0.0) # ----------------------------------------------------------------- @pyqtSlot() def slot_configureCarla(self): dialog = CarlaSettingsW(self, self.host, False, False) if not dialog.exec_(): return self.fParent.loadSettings(False) # ----------------------------------------------------------------- @pyqtSlot(int) def slot_handleReloadAllCallback(self, pluginId): if pluginId >= self.fPluginCount: return pitem = self.fPluginList[pluginId] if pitem is None: return self.fRack.setCurrentRow(-1) self.fCurrentRow = -1 self.fLastSelectedItem = None pitem.recreateWidget() # ----------------------------------------------------------------- @pyqtSlot(int) def slot_currentRowChanged(self, row): self.fCurrentRow = row if self.fLastSelectedItem is not None: self.fLastSelectedItem.setSelected(False) if row < 0 or row >= self.fPluginCount or self.fPluginList[row] is None: self.fLastSelectedItem = None return pitem = self.fPluginList[row] pitem.getWidget().setSelected(True) self.fLastSelectedItem = pitem.getWidget() # ----------------------------------------------------------------- def getPluginItem(self, pluginId): if pluginId >= self.fPluginCount: return None pitem = self.fPluginList[pluginId] if pitem is None: return None if False: pitem = CarlaRackItem(self, 0, False) return pitem def getPluginEditDialog(self, pluginId): if pluginId >= self.fPluginCount: return None pitem = self.fPluginList[pluginId] if pitem is None: return None if False: pitem = CarlaRackItem(self, 0, False) return pitem.getEditDialog() def getPluginSlotWidget(self, pluginId): if pluginId >= self.fPluginCount: return None pitem = self.fPluginList[pluginId] if pitem is None: return None if False: pitem = CarlaRackItem(self, 0, False) return pitem.getWidget()
class MyCodeEditor(QWidget): def __init__(self,parent=None): QWidget.__init__(self,parent) self.__editorSettings = EditorSettings() self.__textDocument = PythonTextDocument() self.__splitter = QSplitter(self) # 横纵滚动条 self.__verticalScrollBar = QScrollBar(self) self.__verticalScrollBar.adjustSize() self.__verticalScrollBar.setMinimumWidth(self.__verticalScrollBar.width()) self.__verticalScrollBar.setMaximumWidth(self.__verticalScrollBar.width()) self.__verticalScrollBar.valueChanged.connect(self.__onVScrollValueChanged) self.__editorSettings.startDisLineNumberChangedSignal.connect(self.__verticalScrollBar.setValue) self.__horizontalScrollBar = QScrollBar(QtCore.Qt.Horizontal,self) self.__horizontalScrollBar.adjustSize() self.__horizontalScrollBar.setMinimumHeight(self.__horizontalScrollBar.height()) self.__horizontalScrollBar.setMaximumHeight(self.__horizontalScrollBar.height()) self.__horizontalScrollBar.valueChanged.connect(self.__onHScrollValueChanged) self.__editorSettings.startDisLetterXOffChangedSignal.connect(self.__horizontalScrollBar.setValue) self.__lineNumberWidget = LineNumberWidget(self.__editorSettings,self.__splitter) setattr(self.__lineNumberWidget,'resizeEvent',self.__onLineNumberWidgetSizeChanged) self.__codeTextWidget = CodeTextWidget(self.__textDocument,self.__editorSettings,self.__splitter) self.__codeTextWidget.document().totalLevelTextChangedSignal.connect(self.__onCodeTextChanged) self.__codeTextWidget.settings().lineTextMaxPixelChangedSignal.connect(self.__onLineStrLengthChanged) self.__codeTextWidget.visibleLineYOffInfoChangedSignal.connect( self.__lineNumberWidget.setVisibleLineYOffInfoArray ) self.__splitter.addWidget( self.__lineNumberWidget ) self.__splitter.addWidget( self.__codeTextWidget ) self.__splitter.setCollapsible( 0,False ) self.__splitter.setCollapsible( 1,False ) self.setText = self.__codeTextWidget.setText self.getText = self.__codeTextWidget.getText def __onLineStrLengthChanged(self,newMaxLength): hMax = newMaxLength-1 self.__horizontalScrollBar.setRange(0,hMax) if self.__horizontalScrollBar.value() > hMax: self.__horizontalScrollBar.setValue(hMax) def __onCodeTextChanged(self,*arg1,**arg2): vMax = self.__codeTextWidget.document().getLineCount()-1 self.__verticalScrollBar.setRange(0,vMax) if self.__verticalScrollBar.value() > vMax: self.__verticalScrollBar.setValue(vMax) def __onVScrollValueChanged(self): self.__codeTextWidget.showLineNumberAsTop(self.__verticalScrollBar.value()) def __onHScrollValueChanged(self): self.__codeTextWidget.showLeftXOffAsLeft(self.__horizontalScrollBar.value()) def __onLineNumberWidgetSizeChanged(self,*arg1,**arg2): lineNumberWidgetWidth = self.__lineNumberWidget.width() vScrollBarWidth = self.__verticalScrollBar.width() hScrollBarHeight = self.__horizontalScrollBar.height() self.__horizontalScrollBar.setGeometry(lineNumberWidgetWidth,self.height()-hScrollBarHeight, \ self.width()-vScrollBarWidth-lineNumberWidgetWidth,hScrollBarHeight) def resizeEvent(self, event): vScrollBarWidth = self.__verticalScrollBar.width() hScrollBarHeight = self.__horizontalScrollBar.height() self.__splitter.setGeometry( 0,0,self.width()-vScrollBarWidth,self.height()-hScrollBarHeight ) self.__verticalScrollBar.setGeometry(self.width()-vScrollBarWidth,0,vScrollBarWidth,self.height()-hScrollBarHeight) self.__onLineNumberWidgetSizeChanged() def wheelEvent(self, event): changedV = 3 if event.angleDelta().y() < 0 else -3 self.__verticalScrollBar.setValue( self.__verticalScrollBar.value() + changedV )
class PdfDrawWidget(QWidget): horizontalScrollbar = None verticalScrollbar = None pdfVis: Document = None pageNum: int = 0 zoom: float = 1 __controlIsPressed = False __pressStart: Tuple[float, float] = None def __init__(self, parent: QWidget = None, painter: QPainter = QPainter()): super().__init__(parent) self.painter = painter self.horizontalScrollbar = QScrollBar(Qt.Horizontal) self.verticalScrollbar = QScrollBar(Qt.Vertical) self.horizontalScrollbar.setVisible(False) self.verticalScrollbar.setVisible(False) self.horizontalScrollbar.valueChanged.connect(lambda: self.update()) self.verticalScrollbar.valueChanged.connect(lambda: self.update()) self.setMouseTracking(True) def paintEvent(self, event: QPaintEvent): """All Drawing Actions are activated here""" self.__drawPDF(event) __viewchanged = True __zoomed = True __pdfImages: List[Tuple[int, QImage]] = [ ] # List of Tuples where first index is the hightoffset __pageoffsets: List[int] = [] def __drawPDF(self, event: QPaintEvent): """Draws the Pdf centered onto the self Object as long as the self.pdfVis variable isn't None. self.verticalScrollbar & self.horizontalScrollbar will be manipulated in range and visibility""" if self.pdfVis is not None: if self.__viewchanged: if self.__zoomed: hightCount = 0 self.__pageoffsets = [0] for page in self.pdfVis.pages(): hightCount += page.rect.height * self.zoom self.__pageoffsets.append(hightCount) hightCount -= self.height() if self.height() < hightCount: self.verticalScrollbar.setRange(0, hightCount) self.verticalScrollbar.setVisible(True) else: self.verticalScrollbar.setVisible(False) self.verticalScrollbar.setRange(0, 0) mat = fitz.Matrix(self.zoom, self.zoom) self.__pdfImages = [] lowestVisablePage = next( i for i in range(len(self.__pageoffsets) - 1) if self.__pageoffsets[i + 1] >= self.verticalScrollbar.value()) try: highestVisablePage = next( i for i in range(len(self.__pageoffsets) - 1) if self.__pageoffsets[i + 1] >= self.verticalScrollbar.value() + self.height()) + 1 except StopIteration: highestVisablePage = self.pdfVis.pageCount for falseI, page in enumerate( self.pdfVis.pages(lowestVisablePage, highestVisablePage)): i = falseI + lowestVisablePage clipx0 = (page.rect.width * self.zoom / 2 - self.width() / 2 + self.horizontalScrollbar.value()) \ if ( page.rect.width * self.zoom / 2 - self.width() / 2 + self.horizontalScrollbar.value()) > 0 else 0 clipy0 = (self.verticalScrollbar.value() - self.__pageoffsets[i]) / self.zoom \ if self.verticalScrollbar.value() >= self.__pageoffsets[i] else 0 # clipx1 = # clipy1 = print(clipy0, clipx0) # print(self.verticalScrollbar.value()) pix: Pixmap = page.getPixmap(mat) # , clip=Rect(0,0,110,110)) fmt = QImage.Format_RGBA8888 if pix.alpha else QImage.Format_RGB888 self.__pdfImages.append((self.__pageoffsets[i], QImage(pix.samples, pix.width, pix.height, pix.stride, fmt))) if self.__pdfImages[0][1].width() > self.width(): self.horizontalScrollbar.setRange( self.width() - self.__pdfImages[0][1].width(), self.__pdfImages[0][1].width() - self.width()) self.horizontalScrollbar.setVisible(True) else: self.horizontalScrollbar.setVisible(False) self.horizontalScrollbar.setRange(0, 0) self.__viewchanged = False self.painter.begin(self) for i, (y, img) in enumerate(self.__pdfImages): self.painter.drawImage( self.painter.viewport().width() / 2 - img.width() / 2 - self.horizontalScrollbar.value(), y + 5 * i - self.verticalScrollbar.value(), img) self.painter.end() else: pass def resizeEvent(self, QResizeEvent): super().resizeEvent(QResizeEvent) def wheelEvent(self, event: QWheelEvent): if self.__controlIsPressed: if self.zoom + 0.005 * event.angleDelta().y() > 0: self.zoom += 0.005 * event.angleDelta().y() else: self.zoom = 0.1 self.__zoomed = True else: self.verticalScrollbar.setValue(self.verticalScrollbar.value() - event.angleDelta().y()) self.__viewchanged = True self.update() def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Control: self.__controlIsPressed = True def keyReleaseEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Control: self.__controlIsPressed = False def mousePressEvent(self, event: QMouseEvent): self.__pressStart = (event.x(), event.y()) def mouseMoveEvent(self, event: QMouseEvent): if self.__pressStart is not None: pass # Todo Draw Rectangle around all Textboxes def loadDocument(self, path: str): self.pdfVis = fitz.Document(path) self.update()
class ObjMotorWidgetUI(QWidget): # waveforms_generated = pyqtSignal(object, object, list, int) # SignalForContourScanning = pyqtSignal(int, int, int, np.ndarray, np.ndarray) # MessageBack = pyqtSignal(str) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # os.chdir('./')# Set directory to current folder. self.setFont(QFont("Arial")) # self.setMinimumSize(1350,900) self.setWindowTitle("ObjMotorWidget") self.layout = QGridLayout(self) self.connect_status = False #************************************************************************************************************************************** #-------------------------------------------------------------------------------------------------------------------------------------- #-----------------------------------------------------------GUI for Objective Motor---------------------------------------------------- #-------------------------------------------------------------------------------------------------------------------------------------- #************************************************************************************************************************************** # Movement based on relative positions. self.ObjMotorcontrolContainer = QGroupBox("Objective motor control") self.ObjMotorcontrolContainer.setStyleSheet("QGroupBox {\ font: bold;\ border: 1px solid silver;\ border-radius: 6px;\ margin-top: 12px;\ color:Navy; \ background-color: #FFFAFA}\ QGroupBox::title{subcontrol-origin: margin;\ left: 7px;\ padding: 5px 5px 5px 5px;}") self.ObjMotorcontrolLayout = QGridLayout() self.ObjMotor_connect = StylishQT.connectButton() self.ObjMotor_connect.setFixedWidth(70) self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_connect, 0, 0) self.ObjMotor_connect.clicked.connect(lambda: self.ConnectMotor()) self.ObjMotor_connect.setGraphicsEffect(QGraphicsDropShadowEffect(blurRadius=3, xOffset=2, yOffset=2)) self.ObjMotor_disconnect = StylishQT.disconnectButton() self.ObjMotor_disconnect.setFixedWidth(70) self.ObjMotor_disconnect.setGraphicsEffect(QGraphicsDropShadowEffect(blurRadius=3, xOffset=2, yOffset=2)) self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_disconnect, 0, 1) self.ObjMotor_disconnect.clicked.connect(lambda: self.DisconnectMotor()) self.ObjMotor_disconnect.setEnabled(False) self.ObjMotor_upwards = QPushButton("↑") self.ObjMotor_upwards.setStyleSheet("QPushButton {color:white;background-color: teal; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}" "QPushButton:pressed {color:red;background-color: white; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}" "QPushButton:hover:!pressed {color:gray;background-color: teal; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}") self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_upwards, 2, 2) self.ObjMotor_upwards.clicked.connect(lambda: self.MovingMotorThread("Motor_move_upwards")) # self.ObjMotor_upwards.setShortcut('w') self.ObjMotor_down = QPushButton("↓") self.ObjMotor_down.setStyleSheet("QPushButton {color:white;background-color: teal; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}" "QPushButton:pressed {color:red;background-color: white; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}" "QPushButton:hover:!pressed {color:gray;background-color: teal; border-style: outset;border-radius: 10px;border-width: 2px;font: bold 14px;padding: 6px}") self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_down, 3, 2) self.ObjMotor_down.clicked.connect(lambda: self.MovingMotorThread("Motor_move_downwards")) # self.stage_down.setShortcut('s') self.ObjMotor_target = QDoubleSpinBox(self) self.ObjMotor_target.setMinimum(-10000) self.ObjMotor_target.setMaximum(10000) self.ObjMotor_target.setDecimals(6) # self.ObjMotor_target.setValue(3.45) self.ObjMotor_target.setSingleStep(0.001) self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_target, 1, 1) self.ObjMotorcontrolLayout.addWidget(QLabel("Target:"), 1, 0) self.ObjMotor_current_pos_Label = QLabel("Current position: ") self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_current_pos_Label, 2, 0, 1, 2) self.ObjMotor_goto = QPushButton() self.ObjMotor_goto.setIcon(QIcon('./Icons/move_coord.png')) self.ObjMotor_goto.setToolTip("Move to absolute position") self.ObjMotor_goto.setStyleSheet("QPushButton {color:white;background-color: #CCFFFF;}" "QPushButton:hover:!pressed {color:white;background-color: #FFE5CC;}") self.ObjMotor_goto.setFixedWidth(35) self.ObjMotor_goto.setFixedHeight(35) self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_goto, 1, 2) self.ObjMotor_goto.clicked.connect(lambda: self.MovingMotorThread("Motor_move_target")) self.ObjMotor_step = QDoubleSpinBox(self) self.ObjMotor_step.setMinimum(-10000) self.ObjMotor_step.setMaximum(10000) self.ObjMotor_step.setDecimals(6) self.ObjMotor_step.setValue(0.003) self.ObjMotor_step.setSingleStep(0.001) self.ObjMotorcontrolLayout.addWidget(self.ObjMotor_step, 3, 1) self.ObjMotorcontrolLayout.addWidget(QLabel("Step: "), 3, 0) self.FocusSlider = QScrollBar(Qt.Horizontal) self.FocusSlider.setMinimum(2500000) self.FocusSlider.setMaximum(4500000) # self.FocusSlider.setTickPosition(QSlider.TicksBothSides) # self.FocusSlider.setTickInterval(1000000) self.FocusSlider.setStyleSheet('color:white; background: lightblue') self.FocusSlider.setSingleStep(10000) # self.line640 = QLineEdit(self) # self.line640.setFixedWidth(60) # self.FocusSlider.sliderReleased.connect(lambda:self.updatelinevalue(640)) self.FocusSlider.valueChanged.connect(lambda:self.MovingMotorThread("Motor_move_slider")) self.FocusSlider.setTracking(False) # self.line640.returnPressed.connect(lambda:self.updatesider(640)) self.ObjMotorcontrolLayout.addWidget(self.FocusSlider, 4, 0, 1, 3) self.ObjMotorcontrolContainer.setLayout(self.ObjMotorcontrolLayout) self.ObjMotorcontrolContainer.setMaximumHeight(300) self.layout.addWidget(self.ObjMotorcontrolContainer, 4, 0) #************************************************************************************************************************************** #-------------------------------------------------------------------------------------------------------------------------------------- #-----------------------------------------------------------Fucs for Motor movement---------------------------------------------------- #-------------------------------------------------------------------------------------------------------------------------------------- #************************************************************************************************************************************** def ConnectMotor(self): self.ObjMotorcontrolContainer.setEnabled(False) self.ObjMotor_disconnect.setEnabled(True) self.ObjMotor_connect.setEnabled(False) self.device_instance = ConnectObj_Thread() self.device_instance.start() self.device_instance.finished.connect(self.getmotorhandle) def getmotorhandle(self): self.pi_device_instance = self.device_instance.getInstance() print('Objective motor connected.') self.connect_status = True # self.normalOutputWritten('Objective motor connected.'+'\n') self.ObjCurrentPos = self.pi_device_instance.pidevice.qPOS(self.pi_device_instance.pidevice.axes) self.ObjMotor_current_pos_Label.setText("Current position: {:.4f}".format(self.ObjCurrentPos['1'])) # Axis here is a string. self.ObjMotor_target.setValue(self.ObjCurrentPos['1']) decimal_places = len(str(self.ObjCurrentPos['1']).split('.')[1]) print(int(self.ObjCurrentPos['1']*(10**decimal_places))) self.FocusSlider.setValue(int(self.ObjCurrentPos['1']*(10**6))) self.ObjMotorcontrolContainer.setEnabled(True) def MovingMotorThread(self, target): if target == "Motor_move_target": MoveMotorThread = threading.Thread(target = self.MoveMotor, args=('Target',)) MoveMotorThread.start() elif target == "Motor_move_upwards": MoveMotorThread = threading.Thread(target = self.MoveMotor, args=('UP',)) MoveMotorThread.start() elif target == "Motor_move_downwards": MoveMotorThread = threading.Thread(target = self.MoveMotor, args=('DOWN',)) MoveMotorThread.start() elif target == "Motor_move_slider": MoveMotorThread = threading.Thread(target = self.MoveMotor, args=('Slider',)) MoveMotorThread.start() def MoveMotor(self, direction): if direction == "Target": pos = PIMotor.move(self.pi_device_instance.pidevice, self.ObjMotor_target.value()) elif direction == "UP": self.MotorStep = self.ObjMotor_step.value() pos = PIMotor.move(self.pi_device_instance.pidevice, (self.ObjCurrentPos['1'] + self.MotorStep)) elif direction == "DOWN": self.MotorStep = self.ObjMotor_step.value() pos = PIMotor.move(self.pi_device_instance.pidevice, (self.ObjCurrentPos['1'] - self.MotorStep)) elif direction == "Slider": pos = PIMotor.move(self.pi_device_instance.pidevice, self.FocusSlider.value()/1000000) self.ObjCurrentPos = self.pi_device_instance.pidevice.qPOS(self.pi_device_instance.pidevice.axes) self.ObjMotor_current_pos_Label.setText("Current position: {:.4f}".format(self.ObjCurrentPos['1'])) # Axis here is a string. self.ObjMotor_target.setValue(self.ObjCurrentPos['1']) # decimal_places = len(str(self.ObjCurrentPos['1']).split('.')[1]) self.FocusSlider.setValue(int(self.ObjCurrentPos['1']*(10**6))) def DisconnectMotor(self): self.ObjMotor_connect.setEnabled(True) self.ObjMotor_disconnect.setEnabled(False) PIMotor.CloseMotorConnection(self.pi_device_instance.pidevice) print('Disconnected') self.connect_status = False # self.normalOutputWritten('Objective motor disconnected.'+'\n') def closeEvent(self, event): # ## Because the software combines both PyQt and PyQtGraph, using the # ## closeEvent() from PyQt will cause a segmentation fault. Calling # ## also the exit() from PyQtGraph solves this problem. # pg.exit() if self.connect_status == True: self.DisconnectMotor() QtWidgets.QApplication.quit() event.accept()
class MainWindow(MainWindowBase, MainWindowUI): VIDEOS = ('front_video_file', 'eyes_video_file') def __init__(self, manager, parent=None): MainWindowBase.__init__(self, parent) self.manager = manager self.current_segment = None self.current_video = 0 self.nav_hide_empty = True self.setupUi(self) self.setupConnections() def setupUi(self, parent): MainWindowUI.setupUi(self, parent) # content area layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.content.setLayout(layout) # add video widget self.contentWidget = VideoWidget() self.content.layout().addWidget(self.contentWidget) self.prev_code = 'def f(img):\n return img' self.te_code = PyCodeEdit() self.te_code.setPlainText(self.prev_code) self.content.layout().addWidget(self.te_code) # footer area layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.footer.setLayout(layout) self.bar_index = QScrollBar(Qt.Horizontal) self.bar_index.setFocusPolicy(Qt.WheelFocus) self.bar_index.setMinimum(0) self.bar_index.setSingleStep(1) self.bar_index.valueChanged.connect(self.indexChanged) layout.addWidget(self.bar_index) self.info = QLabel() layout.addWidget(self.info) # construct navigation tree self.refreshNavigation() # design the view self.treeView.header().hide() # hide header self.treeView.expandToDepth(0) # expand first level def setupConnections(self): # shortcuts self.sc_next = QShortcut(QKeySequence("Right"), self) self.sc_next.activated.connect(self.nextImage) self.sc_prev = QShortcut(QKeySequence("Left"), self) self.sc_prev.activated.connect(self.prevImage) self.treeView.doubleClicked.connect(self.navigation_doubleClicked) self.pb_video_toggle.clicked.connect(self.toggleVideo) self.pb_hide_toggle.clicked.connect(self.toggleHideEmpty) def toggleVideo(self): self.current_video = (self.current_video + 1) % len(MainWindow.VIDEOS) self.setSegment(self.current_segment) def toggleHideEmpty(self): self.nav_hide_empty = not self.nav_hide_empty self.refreshNavigation() def refreshNavigation(self): items = [] for project_id in self.manager.getProjectNames(): project = self.manager.getProject(project_id) p_node = NavigationNode(project.info['Name']) p_node.obj_data = project items.append(p_node) for r_id in sorted(p_node.obj_data.getRecordingNames()): print(r_id) recording = p_node.obj_data.getRecording(r_id) print(recording) if recording: r_node = NavigationNode(r_id) r_node.obj_data = recording p_node.addChild(r_node) for segment_id in r_node.obj_data.getSegmentIDs(): s_node = NavigationNode(segment_id) s_node.obj_data = r_node.obj_data.getSegment( segment_id) r_node.addChild(s_node) self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows) self.treeView.setUniformRowHeights(True) self.treeView.setModel(NavigationModel(items)) def navigation_doubleClicked(self, _): item = self.treeView.selectedIndexes()[0] obj = item.internalPointer().obj_data if hasattr(obj, 'segments') and obj.segments_data: obj = obj.segments_data[0] if hasattr(obj, 'eyes_video_file'): self.setSegment(obj) def applyCode(self): code = self.te_code.toPlainText() if self.prev_code != code: try: exec(code, globals(), locals()) self.contentWidget.onImage = locals()['f'] except Exception as e: print(e) def prevImage(self): self.bar_index.setValue(self.bar_index.value() - 1) def nextImage(self): self.bar_index.setValue(self.bar_index.value() + 1) def setVideo(self, path): self.contentWidget.openVideo(path) self.bar_index.setMaximum(self.contentWidget.video.length) def indexChanged(self, value): self.applyCode() video = self.contentWidget.video video.pos_frame = value self.contentWidget.updateImage() info_msg = [] info_msg.append('FPS: %s' % video.fps) info_msg.append('Frame: %d / %d (%.4f)' % (video.pos_frame + 1, video.length, video.pos_msec)) self.info.setText('\n'.join(info_msg)) def setSegment(self, segment): try: self.current_segment = segment self.setVideo( getattr(self.current_segment, MainWindow.VIDEOS[self.current_video])) self.bar_index.setValue(0) self.indexChanged(0) except: pass