I just want to show different images whenever I press keys.
Different keys are connected to different functions which show different image or do different things.
There is text at first, and after press spacebar key, the text is deleted and 'image 1' is appeared. I want to change image which is shown on screen whenever I press the keyboard button 'F' or 'J'
, but nothing is happened after I press space bar key.
Here are my codes below.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
class StartExp(QWidget):
def __init__(self):
super().__init__()
self.expUI()
def expUI(self):
self.setWindowTitle("ver.1")
self.resize(500, 500)
self.information()
def information(self):
# information
self.info1 = QLabel(f"Hi, there!", self)
self.info1.setAlignment(Qt.AlignCenter)
layout = QVBoxLayout()
layout.addWidget(self.info1)
self.setLayout(layout)
def image1(self):
fix_h = 100
fix_w = 100
self.img1 = QLabel(self)
image1 = QPixmap('1.jpg')
self.img1.setPixmap(image1)
self.img1.move(fix_w, fix_h)
def image2(self):
fix_h = 100
fix_w = 100
self.img2 = QLabel(self)
image2 = QPixmap('2.jpg')
self.img2.setPixmap(image2)
self.img2.move(fix_w, fix_h)
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
elif e.key() ==Qt.Key_F:
self.clearimage2()
self.image1()
self.update()
elif e.key() ==Qt.Key_J:
self.clearimage1()
self.image2()
self.update()
elif e.key() == Qt.Key_Space:
self.clearinfo()
self.image1()
self.update()
def clearinfo(self):
try:
self.info1.clear()
except:
pass
def clearimage1(self):
try:
self.info1.clear()
except:
pass
def clearimage2(self):
try:
self.image2.clear()
except:
pass
def run():
app = QApplication(sys.argv)
mainExp = StartExp()
sys.exit(app.exec_())
run()
Related
In this minimal reproducible example, I have a comboBox and a pushButton. I am trying to activate buttons on the basis of current text selected from the comboBox, but I can't able activate buttons when I tried to verify it first inside if elif else condition, how to activate right function on the basis of current text.
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QWidget):
def __init__(self):
super(QWidget, self).__init__()
main_layout = QVBoxLayout(self)
self.buttons = []
# Works:
self.combo = QComboBox()
main_layout.addWidget(self.combo)
self.combo.addItems(['PHC'])
self.combo.addItems(['CHC'])
self.combo.addItems(['HSC'])
self.combo.addItems(['DH'])
self.combo.addItems(['LSH'])
# # Connecting comboBox to VerifyFType function
self.combo.currentIndexChanged[str].connect(self.VerifyFType)
self.button_2 = QPushButton('Validate', self)
main_layout.addWidget(self.button_2)
self.buttons.append(self.button_2)
def VerifyFType(self):
print("Entered VerifyFType")
FType = self.combo.currentText()
print(FType)
if(FType == "PHC"):
self.button_2.clicked.connect(lambda: self.PHC_Validate)
elif(FType == "CHC"):
self.button_2.clicked.connect(lambda: self.CHC_Validate)
elif(FType == "DH"):
self.button_2.clicked.connect(lambda: self.DH_Validate)
elif(FType == "HSC"):
self.button_2.clicked.connect(lambda: self.HSC_Validate)
elif(FType == "LSH"):
self.button_2.clicked.connect(lambda: self.LSH_Validate)
else:
"Nothing Matched , No such FType"
def PHC_Validate(self):
print('Entered PHC_Validate')
def CHC_Validate(self):
print('Entered CHC_Validate')
def DH_Validate(self):
print('Entered DH_Validate')
def HSC_Validate(self):
print('Entered HSC_Validate')
def LSH_Validate(self):
print('Entered LSH_Validate')
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Your logic is wrong since you seem to think that connecting the signal to another function will disconnect the signal from the previous function.
The solution is to invoke the appropriate function using the currentText of the QComboBox when the button is pressed.
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.combo = QComboBox()
self.combo.addItems(["PHC", "CHC", "HSC", "DH", "LSH"])
self.button_2 = QPushButton("Validate", self)
self.button_2.clicked.connect(self.handle_clicked)
main_layout = QVBoxLayout(self)
main_layout.addWidget(self.combo)
main_layout.addWidget(self.button_2)
def handle_clicked(self):
FType = self.combo.currentText()
if FType == "PHC":
self.PHC_Validate()
elif FType == "CHC":
self.CHC_Validate()
elif FType == "DH":
self.DH_Validate()
elif FType == "HSC":
self.HSC_Validate()
elif FType == "LSH":
self.LSH_Validate()
else:
"Nothing Matched , No such FType"
def PHC_Validate(self):
print("Entered PHC_Validate")
def CHC_Validate(self):
print("Entered CHC_Validate")
def DH_Validate(self):
print("Entered DH_Validate")
def HSC_Validate(self):
print("Entered HSC_Validate")
def LSH_Validate(self):
print("Entered LSH_Validate")
I’m trying to write a GUI application which will add a 'Delete' button when you press the 'Clear' button, and 'Clear' must turn to 'Add'. The 'Delete' button should be added to a QHBoxLayout and then when you press 'Add' - it will delete the 'Delete' button from the QHBoxLayout.
Ive tried finding the button ive added and using deleteLater() on it - but it gives me a run time error (the type which i get is QWidget and not QPushButton).
Ive tried casting the item to QPushButton and then using deleteLater() - still doesnt work.
Any help is welcome.
def add_image(self, button_index):
try:
file_path = QFileDialog.getOpenFileName(self, 'Open Image', '*.jpg')
except FileNotFoundError:
self.status_bar.showMessage('The path {} is not valid'.format(file_path))
else:
if file_path[0] != '':
new_image=QPixmap(file_path[0]).scaled(self.image_height,self.image_width)
self.image_label_list[button_index].setPixmap(new_image)
self.button_list[button_index].setText('Remove')
self.status_bar.showMessage(
'Image {} was added successfully!'.format(get_name_from_path(file_path[0]))
)
if self.button_layout_list[button_index].count() > 1:
delete_button = type(PyQt5.QtWidgets.QPushButton)(self.button_layout_list[button_index].itemAt(1))
delete_button.deleteLater()
self.button_layout_list[button_index].removeWidget(self.button_layout_list[button_index].itemAt(1))
print('number of items: {}'.format(self.button_layout_list[button_index].count()))
if (button_index - (len(self.button_list) - 1)) == 0:
empty_image_layout = QVBoxLayout()
button_box_layout = QHBoxLayout()
empty_pic_label = QLabel()
empty_pic = QPixmap('empty p.png').scaled(self.image_height, self.image_width)
empty_pic_label.setPixmap(empty_pic)
add_button = QPushButton('Add')
# add_button.setFixedWidth(self.image_width)
add_button.clicked.connect(self.on_click)
button_box_layout.addWidget(add_button)
empty_image_layout.addWidget(empty_pic_label)
empty_image_layout.addLayout(button_box_layout)
item = self.image_box.itemAt(self.stretch_index)
self.image_box.removeItem(item)
self.image_box.addLayout(empty_image_layout)
self.image_box.addStretch()
self.stretch_index += 1
# Book keeping
self.image_layout_list.append(empty_image_layout)
self.button_layout_list.append(button_box_layout)
self.image_label_list.append(empty_pic_label)
self.button_list.append(add_button)
def remove_image(self, button_id, button_index):
image_label = self.image_label_list[button_index]
image_label.setPixmap(self.empty_pic)
button_id.setText('Add')
delete_button = QPushButton('Delete')
print(type(delete_button))
print(self.button_layout_list[button_index].count())
self.button_layout_list[button_index].addWidget(delete_button)
Try it:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(500, 100, 300, 200)
self.setWindowTitle("PushButton - `Clear` -> `Add` + `Delete`")
self.setWindowIcon(QIcon('E:\\_Qt\\img\\qt-logo.png'))
self.layout = QHBoxLayout()
self.btn = QPushButton("Clear")
self.btn.clicked.connect(self.buttonPress)
self.layout.addWidget(self.btn)
self.btnDelete = QPushButton("Delete")
self.btnDelete.clicked.connect(self.buttonDelete)
self.setLayout(self.layout)
self.show()
def buttonPress(self):
sender = self.sender()
if sender.text() == "Clear":
self.btn.setText("Add")
self.layout.addWidget(self.btnDelete)
self.btnDelete.show()
elif sender.text() == "Add":
print("sender - self.btn", sender.text())
self.btnDelete.hide()
self.btn.setText("Clear")
def buttonDelete(self):
print("You pressed the button `{}`".format(self.sender().text()))
if __name__ == '__main__':
app = QApplication(sys.argv)
test = Window()
#test.show()
sys.exit(app.exec_())
I'm trying to update a QLineEdit when I do a wheel move on the mouse and if I press a number on the keyboard at the same time. Unfortunatly, I don't see a mouse wheel event for QLineEdit widget so I don't understand how I can set a signal to each QLineEdit. The other issue I have is as the QLineEdit are already in a scroll bar environment, I cannot detect all wheel event because the scroll is done first.
For instance with this code:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralTabs= QTabWidget()
self.setCentralWidget(self.centralTabs)
self.setFixedWidth(200)
self.setFixedHeight(200)
#tab Model selection
self.tab_ModelSelect = QWidget()
self.centralTabs.addTab(self.tab_ModelSelect,"Label")
self.groupscrolllayouttest = QHBoxLayout() ####
self.groupscrollbartest = QGroupBox() ####
self.mainHBOX_param_scene = QVBoxLayout()
for i in range(10):
LineEdit = QLineEdit(str(i))
LineEdit.setFixedWidth(200)
self.mainHBOX_param_scene.addWidget(LineEdit)
self.installEventFilter(self)
scroll = QScrollArea()
widget = QWidget(self)
widget.setLayout(QVBoxLayout())
widget.layout().addWidget(self.groupscrollbartest)
scroll.setWidget(widget)
scroll.setWidgetResizable(True)
self.groupscrollbartest.setLayout(self.mainHBOX_param_scene)
self.groupscrolllayouttest.addWidget(scroll)
self.tab_ModelSelect.setLayout(self.groupscrolllayouttest)
def eventFilter(self, widget, event):
if (event.type() == QEvent.Wheel) :
# get which key is pressed
# if the key is a number, put the number in 'num' variable
# get on which QLineEdit the wheel was make
# set the text of that QLineEdit to previous value +- num
event.ignore()
return QWidget.eventFilter(self, widget, event)
def main():
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
# ex.showMaximized()
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
I tried to something with wheelevent but as mention, I don't enter in this function because the scroll bar is activated first. I tried to test if the wheel event happend on a QLineEdit but I even struggle to do that...
What I'm seeking to do is when I do a wheelevent with the mouse on a QlineEdit with the '5' key pressed, I want increase or decrease the QLineEdit text by 5 according to the direction of the mouse wheel.
I red some post with eventfilter (as How to get Click Event of QLineEdit in Qt?) but I don't understand how does this work.
In my eventFilter function, I need to do several step:
# get which key is pressed
# if the key is a number, put the number in 'num' variable
# get on which QLineEdit the wheel was make
# set the text of that QLineEdit to previous value +- num
but I don't know how to make them. In particular getting the pressed key and knowing on which QlineEdit the wheel was made.
If you wish that all QLineEdit have that behavior then it is appropriate that you create your own class and overwrite the necessary events, to avoid that when you move the scroll when the pointer is inside the QLineEdit and pressing an established key, we accept the event so that it does not propage.
Another recommendation is not to use the 5 key since this is a text that QLineEdit can handle causing problems, for this you can use the SHIFT key:
class LineEdit(QLineEdit):
KEY = Qt.Key_Shift
def __init__(self, *args, **kwargs):
QLineEdit.__init__(self, *args, **kwargs)
self.isKeyPressed = False
def keyPressEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = True
QLineEdit.keyPressEvent(self, event)
def keyReleaseEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = False
QLineEdit.keyReleaseEvent(self, event)
def wheelEvent(self, event):
if self.isKeyPressed:
delta = 1 if event.angleDelta().y() > 0 else -1
fn = self.font()
fn.setPointSize(fn.pointSize() + delta)
self.setFont(fn)
event.accept()
The complete example:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class LineEdit(QLineEdit):
KEY = Qt.Key_Shift
def __init__(self, *args, **kwargs):
QLineEdit.__init__(self, *args, **kwargs)
self.isKeyPressed = False
def keyPressEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = True
QLineEdit.keyPressEvent(self, event)
def keyReleaseEvent(self, event):
if event.key() == LineEdit.KEY:
self.isKeyPressed = False
QLineEdit.keyReleaseEvent(self, event)
def wheelEvent(self, event):
if self.isKeyPressed:
delta = 1 if event.angleDelta().y() > 0 else -1
fn = self.font()
fn.setPointSize(fn.pointSize() + delta)
self.setFont(fn)
event.accept()
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.centralTabs= QTabWidget()
self.setCentralWidget(self.centralTabs)
self.setFixedWidth(200)
self.setFixedHeight(200)
#tab Model selection
self.tab_ModelSelect = QWidget()
self.centralTabs.addTab(self.tab_ModelSelect,"Label")
self.groupscrolllayouttest = QHBoxLayout() ####
self.groupscrollbartest = QGroupBox() ####
self.mainHBOX_param_scene = QVBoxLayout()
for i in range(10):
le = LineEdit(str(i))
le.setFixedWidth(200)
self.mainHBOX_param_scene.addWidget(le)
self.installEventFilter(self)
scroll = QScrollArea()
widget = QWidget(self)
widget.setLayout(QVBoxLayout())
widget.layout().addWidget(self.groupscrollbartest)
scroll.setWidget(widget)
scroll.setWidgetResizable(True)
self.groupscrollbartest.setLayout(self.mainHBOX_param_scene)
self.groupscrolllayouttest.addWidget(scroll)
self.tab_ModelSelect.setLayout(self.groupscrolllayouttest)
def main():
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
# ex.showMaximized()
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
How could I archive this:
- I need to drag and drop a tab from its tabBar to other tabBar in a splitted widget?
I already subclass the QtabBar and implement the drag and drop events, i already can drag it with the right pixmap and etc, and also i can drop it into the same tabBar, but not in the other one ..
got this error in the output telling me that im not providing the right arguments, here is the code, that i simplified for make it and example, and plus a .JPG of the window.
class EsceneTest(qg.QMainWindow):
def __init__(self,parent=getMayaWindow()):
super(EsceneTest,self).__init__(parent)
#---------------------------------------------------------#
#check for open Window first
winName = windowTitle
if cmds.window(winName, exists =1):
cmds.deleteUI(winName, wnd=True)
self.setAttribute(qc.Qt.WA_DeleteOnClose)
self._initUI()
def _initUI(self):
self.setObjectName(windowObject)
self.setWindowTitle(windowTitle)
self.setMinimumWidth(450)
self.setMinimumHeight(500)
self.resize(1080, 800) # re-size the window
centralWidget = qg.QWidget()
centralWidget.setObjectName('centralWidget')
self.setCentralWidget(centralWidget)
central_layout = qg.QVBoxLayout(centralWidget)
######################
# tab container
#
self.tabWidget = qg.QTabWidget()
self.tabWidget.setAcceptDrops(True)
self.tab_layout = qg.QVBoxLayout(self.tabWidget)
central_layout.addWidget(self.tabWidget)
#######################
# TabBar
#
custom_tabbar = ColtabBar()
self.tabWidget.setTabBar(custom_tabbar)
#######################
# ViewportTab
#
tabCentral_wdg = qg.QWidget()
self.top_lyt = qg.QVBoxLayout(tabCentral_wdg)
self.tab_layout.addLayout(self.top_lyt)
fixedHBox_lyt = qg.QHBoxLayout()
self.top_lyt.addLayout(fixedHBox_lyt)
self.tabWidget.addTab(tabCentral_wdg,'- Viewport')
#######################
# Example ExtraTab
#
tabTwo_wdg = qg.QWidget()
tabTwo_wdg_lyt = qg.QHBoxLayout(tabTwo_wdg)
self.tab_layout.addLayout(tabTwo_wdg_lyt)
label = qg.QLabel(' -- This is an example -- ')
label.setStyleSheet("""
background : qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(53, 57, 60), stop:1 rgb(33, 34, 36));
border-style : none;
font-size: 40px;
font-family: Calibri;
color : rgb(200,200,100);
""")
label.setAlignment(qc.Qt.AlignVCenter | qc.Qt.AlignHCenter )
tabTwo_wdg_lyt.addWidget(label)
tab_panel_lyt = qg.QVBoxLayout(label)
self.tabWidget.addTab(tabTwo_wdg,'- ExtraExample')
############################
# Q Splitter Widget to insert the dragged Tabs
#
split = qg.QSplitter(qc.Qt.Orientation.Vertical, self)
central_layout.addWidget(split)
tab_splitted = qg.QTabWidget()
split.setLayout(qg.QVBoxLayout())
split.insertWidget(0,tab_splitted)
tabBar_2 = ColtabBar()
tab_splitted.setTabBar(tabBar_2)
tabBar_2.addTab('- Insert-Here')
#---------------------------------------------------------------------------------------------#
class ColtabBar(qg.QTabBar):
def __init__(self):
super(ColtabBar, self).__init__()
self.indexTab = None
self.setAcceptDrops(True)
##################################
# Events
def mouseMoveEvent(self, e):
if e.buttons() != qc.Qt.MiddleButton:
return
globalPos = self.mapToGlobal(e.pos())
posInTab = self.mapFromGlobal(globalPos)
self.indexTab = self.tabAt(e.pos())
tabRect = self.tabRect(self.indexTab)
pixmap = qg.QPixmap(tabRect.size())
self.render(pixmap,qc.QPoint(),qg.QRegion(tabRect))
mimeData = qc.QMimeData()
drag = qg.QDrag(self)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
cursor = qg.QCursor(qc.Qt.OpenHandCursor)
drag.setHotSpot(e.pos() - posInTab)
drag.setDragCursor(cursor.pixmap(),qc.Qt.MoveAction)
dropAction = drag.exec_(qc.Qt.MoveAction)
def mousePressEvent(self, e):
#super(qg.QWidget).mousePressEvent(e)
if e.button() == qc.Qt.RightButton:
print('press')
if e.button() == qc.Qt.LeftButton:
globalPos = self.mapToGlobal(e.pos())
posInTab = self.mapFromGlobal(globalPos)
self.indexTab = self.tabAt(e.pos())
self.setCurrentIndex(self.indexTab)
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
e.setDropAction(qc.Qt.MoveAction)
e.accept()
self.insertTab(self.indexTab, self.tabText(self.indexTab))
self.removeTab(self.indexTab)
the ColtabBar is the subclass where im doing the drag and drop events.
IMAGE - >
After many hours and have eaten many manyyyy pages of Qt today over the web, I did it in my way, now I can drag and drop tabs from one tabBar to the other and vice-versa and not just from selection the current tab, i could select every tab that I want in my tab bar and will show me the pixmap of the little tab while dragging...
Here is the code:
** EDITED **
I made it more bullet proof, I had a bug when I was using more than 2 tabs with the index, now is working better, and when I drop it in the same widget it return the event and not execute the code, plus the hovering tabs select with the right mouse button as well .. I hope this can help anybody in the future.
TABINDEX = int()
def getTabIndex(index):
global TABINDEX
if index == -1 or index == TABINDEX:
return
TABINDEX = index
print (TABINDEX)
return TABINDEX
class ColtTab(qg.QTabWidget):
def __init__(self):
super(ColtTab,self).__init__()
self.setAcceptDrops(True)
self.tabBar = self.tabBar()
self.tabBar.setMouseTracking(True)
self.setDocumentMode(True)
self.indexTab = int()
self.setMovable(True)
self.setStyleSheet(style_sheet_file)
# test for hovering and selecting tabs automatic while mouser over then - not working for now...
def eventFilter(self, obj, event):
if obj == self.tabBar:
if event.type() == qc.QEvent.MouseMove:
index=self.tabBar.tabAt(event.pos())
self.tabBar.setCurrentIndex (index)
return True
else:
return
else:
return
##################################
# Events
#
def mouseMoveEvent(self, e):
if e.buttons() != qc.Qt.MiddleButton:
return
globalPos = self.mapToGlobal(e.pos())
#print(globalPos)
tabBar = self.tabBar
#print(tabBar)
posInTab = tabBar.mapFromGlobal(globalPos)
#print(posInTab)
self.indexTab = tabBar.tabAt(e.pos())
#print(self.indexTab)
tabRect = tabBar.tabRect(self.indexTab)
#print(tabRect)
#print(tabRect.size())
pixmap = qg.QPixmap(tabRect.size())
tabBar.render(pixmap,qc.QPoint(),qg.QRegion(tabRect))
mimeData = qc.QMimeData()
drag = qg.QDrag(tabBar)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
cursor = qg.QCursor(qc.Qt.OpenHandCursor)
drag.setHotSpot(e.pos() - posInTab)
drag.setDragCursor(cursor.pixmap(),qc.Qt.MoveAction)
dropAction = drag.exec_(qc.Qt.MoveAction)
def mousePressEvent(self, e):
if e.button() == qc.Qt.RightButton:
self.tabBar.installEventFilter(self)
print('Right button pressed')
super(ColtTab, self).mousePressEvent(e)
def dragEnterEvent(self, e):
e.accept()
if e.source().parentWidget() != self:
return
# Helper function for retrieving the Tab index into a global Var
getTabIndex(self.indexOf(self.widget(self.indexTab)))
def dragLeaveEvent(self,e):
e.accept()
def dropEvent(self, e):
if e.source().parentWidget() == self:
return
e.setDropAction(qc.Qt.MoveAction)
e.accept()
counter = self.count()
if counter == 0:
self.addTab(e.source().parentWidget().widget(TABINDEX),e.source().tabText(TABINDEX))
else:
self.insertTab(counter + 1 ,e.source().parentWidget().widget(TABINDEX),e.source().tabText(TABINDEX))
print ('Tab dropped')
def mouseReleaseEvent(self, e):
if e.button() == qc.Qt.RightButton:
print('Right button released')
self.tabBar.removeEventFilter(self)
super(ColtTab, self).mouseReleaseEvent(e)
#---------------------------------------------------------------------------------#
Pic ->
Found this thread useful. Used your solution to create a self contained generic example in PyQt5. May help someone in the future.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Tabs(QTabWidget):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.setAcceptDrops(True)
self.tabBar = self.tabBar()
self.tabBar.setMouseTracking(True)
self.indexTab = None
self.setMovable(True)
self.addTab(QWidget(self), 'Tab One')
self.addTab(QWidget(self), 'Tab Two')
def mouseMoveEvent(self, e):
if e.buttons() != Qt.RightButton:
return
globalPos = self.mapToGlobal(e.pos())
tabBar = self.tabBar
posInTab = tabBar.mapFromGlobal(globalPos)
self.indexTab = tabBar.tabAt(e.pos())
tabRect = tabBar.tabRect(self.indexTab)
pixmap = QPixmap(tabRect.size())
tabBar.render(pixmap,QPoint(),QRegion(tabRect))
mimeData = QMimeData()
drag = QDrag(tabBar)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
cursor = QCursor(Qt.OpenHandCursor)
drag.setHotSpot(e.pos() - posInTab)
drag.setDragCursor(cursor.pixmap(),Qt.MoveAction)
dropAction = drag.exec_(Qt.MoveAction)
def dragEnterEvent(self, e):
e.accept()
if e.source().parentWidget() != self:
return
print(self.indexOf(self.widget(self.indexTab)))
self.parent.TABINDEX = self.indexOf(self.widget(self.indexTab))
def dragLeaveEvent(self,e):
e.accept()
def dropEvent(self, e):
print(self.parent.TABINDEX)
if e.source().parentWidget() == self:
return
e.setDropAction(Qt.MoveAction)
e.accept()
counter = self.count()
if counter == 0:
self.addTab(e.source().parentWidget().widget(self.parent.TABINDEX),e.source().tabText(self.parent.TABINDEX))
else:
self.insertTab(counter + 1 ,e.source().parentWidget().widget(self.parent.TABINDEX),e.source().tabText(self.parent.TABINDEX))
class Window(QWidget):
def __init__(self):
super().__init__()
self.TABINDEX = 0
tabWidgetOne = Tabs(self)
tabWidgetTwo = Tabs(self)
layout = QHBoxLayout()
self.moveWidget = None
layout.addWidget(tabWidgetOne)
layout.addWidget(tabWidgetTwo)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
This is modified from someone elses code, perhaps one of the examples above.
Anyhow, it's a minimal code for tab-to-tab or tab-to-window drag / droping of tab's contents.
from PyQt5.QtWidgets import QTabWidget
from PyQt5.QtCore import Qt, QPoint, QMimeData
from PyQt5.QtGui import QPixmap, QRegion, QDrag, QCursor
class TabWidget(QTabWidget):
def __init__(self, parent=None, new=None):
super().__init__(parent)
self.setAcceptDrops(True)
self.tabBar().setMouseTracking(True)
self.setMovable(True)
if new:
TabWidget.setup(self)
def __setstate__(self, data):
self.__init__(new=False)
self.setParent(data['parent'])
for widget, tabname in data['tabs']:
self.addTab(widget, tabname)
TabWidget.setup(self)
def __getstate__(self):
data = {
'parent' : self.parent(),
'tabs' : [],
}
tab_list = data['tabs']
for k in range(self.count()):
tab_name = self.tabText(k)
widget = self.widget(k)
tab_list.append((widget, tab_name))
return data
def setup(self):
pass
def mouseMoveEvent(self, e):
if e.buttons() != Qt.RightButton:
return
globalPos = self.mapToGlobal(e.pos())
tabBar = self.tabBar()
posInTab = tabBar.mapFromGlobal(globalPos)
index = tabBar.tabAt(e.pos())
tabBar.dragged_content = self.widget(index)
tabBar.dragged_tabname = self.tabText(index)
tabRect = tabBar.tabRect(index)
pixmap = QPixmap(tabRect.size())
tabBar.render(pixmap,QPoint(),QRegion(tabRect))
mimeData = QMimeData()
drag = QDrag(tabBar)
drag.setMimeData(mimeData)
drag.setPixmap(pixmap)
cursor = QCursor(Qt.OpenHandCursor)
drag.setHotSpot(e.pos() - posInTab)
drag.setDragCursor(cursor.pixmap(),Qt.MoveAction)
drag.exec_(Qt.MoveAction)
def dragEnterEvent(self, e):
e.accept()
#self.parent().dragged_index = self.indexOf(self.widget(self.dragged_index))
def dragLeaveEvent(self,e):
e.accept()
def dropEvent(self, e):
if e.source().parentWidget() == self:
return
e.setDropAction(Qt.MoveAction)
e.accept()
tabBar = e.source()
self.addTab(tabBar.dragged_content, tabBar.dragged_tabname)
if __name__ == '__main__':
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout
import sys
class Window(QWidget):
def __init__(self):
super().__init__()
self.dragged_index = None
tabWidgetOne = TabWidget(self)
tabWidgetTwo = TabWidget(self)
tabWidgetOne.addTab(QWidget(), "tab1")
tabWidgetTwo.addTab(QWidget(), "tab2")
layout = QHBoxLayout()
self.moveWidget = None
layout.addWidget(tabWidgetOne)
layout.addWidget(tabWidgetTwo)
self.setLayout(layout)
app = QApplication(sys.argv)
window = Window()
window1 = Window()
window.show()
window1.show()
sys.exit(app.exec_())
I have a QDialog window that has a continue button. The continue button is the default button because whenever I press the enter key, the continue button is pressed. I discovered something strange: when I press the enter key three times, the continue button presses three times. However, when I press it a fourth time, the whole window closes. I have a cancel button right below the continue button that closes the window, but I don't make the cancel button the default button or anything.
I wanted to override the keyPressEvent so that whenever I'm in the window, the enter button will always be connected to the continue button.
This is what I have right now:
class ManualBalanceUI(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal()
def __init__(self, cls):
super(QtGui.QWidget, self).__init__()
self.window = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint)
self.ui = uic.loadUi('ManualBalanceUI.ui', self.window)
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(ManualBalanceUI, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
self.window.close() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
...
...
However, this doesn't seem to be doing anything right now. Pressing 'Q' doesn't close the window, and I can't really tell if the 'enter' key is working or not.
I looked at this question beforehand: PyQt Connect to KeyPressEvent
I also reviewed all the documentation on SourceForge. Any help would be greatly appreciated!
You can do two ways and one is simply re implement keyPressevent with out any fancy work. Like this
from PyQt4 import QtCore, QtGui
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater()
elif event.key() == QtCore.Qt.Key_Enter:
self.proceed()
event.accept()
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Or as you tried with signals, in your case you where missing to implement this signal properly, here is updated version.
class Example(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(Example, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you're looking at this in 2019, and If Achayan's method does not work for you then check a couple things :
1) Is the keyPressEvent overridden in a child of the main window or main widget? The child's function will override the methods on the parent (at least when using a QMainWindow with setCentralWidget). If this is the case, then the signal might not be emitted like you expect
2) Do you have a widget that handles key inputs differently than QWidget? For example, if the focus is in a QTextEdit object, then key inputs will not be sent to keyPressEvent. Shift focus to another widget
For example, observe the output of the following :
class myDialog(QtWidgets.QDialog):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.keyPressed.connect(self.on_key)
leftGroupBox = QtWidgets.QGroupBox('A Group Label')
text = QtWidgets.QTextEdit('Enter some text')
layout = QtWidgets.QVBoxLayout()
layout.addWidget(text)
leftGroupBox.setLayout(layout)
rightGroupBox = QtWidgets.QGroupBox('Label Options')
label1 = QtWidgets.QCheckBox('ahu')
layout = QtWidgets.QVBoxLayout()
layout.addWidget(label1)
rightGroupBox.setLayout(layout)
# Create the main layout
mainLayout = QtWidgets.QGridLayout()
mainLayout.addWidget(leftGroupBox)
mainLayout.addWidget(rightGroupBox)
self.setLayout(mainLayout)
def keyPressEvent(self, event):
# keyPressEvent defined in child
print('pressed from myDialog: ', event.key())
# self.keyPressed.emit(event) # Emit is hidden in child
def on_key(self, event):
print('event received # myDialog')
if event.key() == QtCore.Qt.Key_0:
print(0)
class MainWindow(QtWidgets.QMainWindow):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(MainWindow, self).__init__()
self.keyPressed.connect(self.on_key)
self.setCentralWidget(myDialog())
self.show()
def keyPressEvent(self, event):
super(MainWindow, self).keyPressEvent(event)
print('pressed from MainWindow: ', event.key())
self.keyPressed.emit(event)
def on_key(self, event):
print('event received # MainWindow')
if event.key() == QtCore.Qt.Key_0:
print(0)
if __name__ == '__main__':
ex = MainWindow()
Output # console : (no event is received #myDialog OR MainWindow)
pressed from myDialog: 48
For Achayan's answer, I succeeded with the code.
It may be the enter key and the return key.
Try Key_Enter and Key_Return. They are different on my keyboard.
QtCore.QObject.connect(self.ui.search_box, QtCore.SIGNAL("textChanged()"), self.fucn1)
Whenever text is changed in search_box function fucn1 is called.
Works for pyqt4