I am trying to create a window with a label and i get this error
File "ui.py", line 16, in mainWindow = MyForm() File
"ui.py", line 9, in init lbl = QtGui.QLable('Welcome Brats!',
self) ttributeError: 'module' object has no attribute 'QLable'
import sys
from PyQt4 import QtGui
class MyForm(QtGui.QWidget):
def __init__(self):
super(MyForm, self).__init__()
lbl = QtGui.QLable('Welcome Brats!', self)
self.setGeometry(300,300,250,150)
self.setWindowTitle(('Port Scaner'))
self.show()
app = QtGui.QApplication(sys.argv)
mainWindow = MyForm()
status = app.exec_()
sys.exit(status)
Pyqt4 python3.4
Related
I'm trying to use the closeEvent function when the user press X on main window but Python never fired closeEvent function.
I read many posts about this issue but eventually I was not succeeded to resolve this.
Any ideas why?
Here is the code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QAction, QMessageBox, QMenu, QWidget
class Ui_MainWindow(object):
def __init__(self):
super(Ui_MainWindow, self).__init__()
print("Initialization succeeded")
def closeEvent(self, event):
print("closeEvent has been called")
userResult = QMessageBox.question(None, "Quit", "Do you want to close the program?", QMessageBox.Yes,
QMessageBox.No)
if userResult == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1920, 1080)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("Milvus UI", "Milvus UI"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
when i add pushbutton dynamically to the QGraphicScene with a pic its work but when i use QPainter to draw a line or rectangle not show.
code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QIcon,QPixmap,QPainter,QPainterPath,QBrush,QColor,QPen
class Scene(QtWidgets.QGraphicsScene):
def __init__(self, *args, **kwargs):
super(Scene, self).__init__(*args, **kwargs)
self.path_item = self.addPath(QtGui.QPainterPath())
self.start_point = QtCore.QPointF()
self.end_point = QtCore.QPointF()
def mousePressEvent(self, event):
self.start_point = event.scenePos()
self.end_point = self.start_point
self.update_path()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() & QtCore.Qt.LeftButton:
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseReleaseEvent(event)
def update_path(self):
if not self.start_point.isNull() and not self.end_point.isNull():
path = QtGui.QPainterPath()
path.moveTo(self.start_point)
path.lineTo(self.end_point)
self.path_item.setPath(path)
def main():
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QGraphicsView()
view.setRenderHint(QtGui.QPainter.Antialiasing)
view.setMouseTracking(True)
pix = QPixmap('assets/data.png')
mainpic = QtWidgets.QGraphicsPixmapItem(pix)
scene = Scene()
scene.addItem(mainpic)
view.setScene(scene)
view.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I think my problem in mouse event but if i disable pic in GraphicsScene draw line correctly worked.
I have been trying to connect to a Bluetooth device (regular, not low energy - an HC-06) using PyQt5 but with no success. I can connect to the same device using standard python calls. I am running Python 3.7 on MacOS. When I run the below code, I get the error: 'unknown error', I'd be happy to know what I am doing wrong.
import sys
import bluetooth
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth
class bluetoothTest(QWidget):
def __init__(self, parent = None):
super(bluetoothTest, self).__init__(parent)
self.connectToRobot()
self.app = QApplication(sys.argv)
self.win = QWidget()
self.win.show()
sys.exit(self.app.exec_())
def connectToRobot(self):
self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)
self.sock.connected.connect(self.connectedToBluetooth)
self.sock.readyRead.connect(self.receivedBluetoothMessage)
self.sock.disconnected.connect(self.disconnectedFromBluetooth)
self.sock.error.connect(self.socketError)
port = 1
self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)
def socketError(self,error):
print(self.sock.errorString())
def connectedToBluetooth(self):
self.sock.write('A'.encode())
def disconnectedFromBluetooth(self):
self.print('Disconnected from bluetooth')
def receivedBluetoothMessage(self):
while sock.canReadLine():
line = sock.readLine()
print(line)
def main():
# deal with a bluetooth bug on mac
if sys.platform == 'darwin':
os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'
app = QApplication(sys.argv)
ex = bluetoothTest()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The problem with my code was the mixing of "regular" Bluetooth and Qt Bluetooth functions, in particular this line:
self.sock = QtBluetooth.QBluetoothSocket(bluetooth.RFCOMM)
which should have been
self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)
Here is the complete working code example:
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtBluetooth
class bluetoothTest(QWidget):
def __init__(self, parent = None):
super(bluetoothTest, self).__init__(parent)
self.connectToRobot()
self.win = QWidget()
self.win.show()
def connectToRobot(self):
self.sock = QtBluetooth.QBluetoothSocket(QtBluetooth.QBluetoothServiceInfo.RfcommProtocol)
self.sock.connected.connect(self.connectedToBluetooth)
self.sock.readyRead.connect(self.receivedBluetoothMessage)
self.sock.disconnected.connect(self.disconnectedFromBluetooth)
self.sock.error.connect(self.socketError)
port = 1
self.sock.connectToService(QtBluetooth.QBluetoothAddress("98:D3:C1:FD:2C:46"),port)
def socketError(self,error):
print(self.sock.errorString())
def connectedToBluetooth(self):
self.sock.write('A'.encode())
def disconnectedFromBluetooth(self):
self.print('Disconnected from bluetooth')
def receivedBluetoothMessage(self):
while self.sock.canReadLine():
line = self.sock.readLine()
print(str(line, "utf-8"))
def main():
# deal with a bluetooth bug on mac
if sys.platform == 'darwin':
os.environ['QT_EVENT_DISPATCHER_CORE_FOUNDATION'] = '1'
app = QApplication(sys.argv)
ex = bluetoothTest()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I tried:
self.installEventFilter(self)
and:
desktop= QApplication.desktop()
desktop.installEventFilter(self)
With:
def eventFilter(self, source, event):
if event.type() == QEvent.MouseMove:
print(event.pos())
return QMainWindow.eventFilter(self, source, event)
In QMainWindow object but nothing conclusive.
Do you have any idea?
Mouse events are initially handled by the window-manager, which then passes them on to whatever window is in that region of the screen. So if there are no Qt windows in that region, you won't get any events (including mouse events).
However, it is still possible to track the cursor position via polling:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
cursorMove = QtCore.pyqtSignal(object)
def __init__(self):
super(Window, self).__init__()
self.cursorMove.connect(self.handleCursorMove)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(50)
self.timer.timeout.connect(self.pollCursor)
self.timer.start()
self.cursor = None
def pollCursor(self):
pos = QtGui.QCursor.pos()
if pos != self.cursor:
self.cursor = pos
self.cursorMove.emit(pos)
def handleCursorMove(self, pos):
print(pos)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 500, 200, 200)
window.show()
sys.exit(app.exec_())
I am writing an application that allows a user to place images on a QGraphicsScene (contained within a QGraphicsView) by clicking on a blank area and then move them about using mousemoveevent. The images are created using a subclassed QGraphicsPixmapItem.
Here's the problem: The very first attempt at moving an item works as expected. However, for all subsequent moves the selected item immediately jumps to the upper left corner of the scene. Here is the code:
import sys
from PySide import QtGui,QtCore
class TestPixmapItem(QtGui.QGraphicsPixmapItem):
def __init__(self, imagename, position, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
px = QtGui.QPixmap(imagename)
self.setPixmap(px)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
# set position
self.setPos(position.x(),position.y())
def mouseReleaseEvent(self,e):
self.setSelected(False)
def mouseMoveEvent(self, e):
QtGui.QGraphicsPixmapItem.mouseMoveEvent(self, e)
class GfxScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
#build parent user interface
super(GfxScene, self).__init__(parent)
def mousePressEvent(self, e):
if(self.itemAt(e.scenePos().x(),e.scenePos().y()) == None):
pixmapItem = TestPixmapItem('test.png',e.scenePos())
self.addItem(pixmapItem)
else:
QtGui.QGraphicsScene.mousePressEvent(self,e);
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
scene = GfxScene(self)
scene.setSceneRect(QtCore.QRect(0, 0, 800, 800))
view = QtGui.QGraphicsView()
view.setScene(scene)
view.setSceneRect(scene.sceneRect())
#view.setGeometry(QtCore.QRect(0, 0, 800, 800))
self.setCentralWidget(view)
def main():
#This function means this was run directly, not called from another python file.
app = QtGui.QApplication.instance()
if app == None:
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Any help would be appreciated!
You should call the QtGui.QGraphicsPixmapItem.mouseReleaseEvent(self, e) when you override the mouse release event, see : http://goo.gl/ChSYP
import sys
from PySide import QtGui,QtCore
class TestPixmapItem(QtGui.QGraphicsPixmapItem):
def __init__(self, imagename, position, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
px = QtGui.QPixmap(imagename)
self.setPixmap(px)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
# set position
self.setPos(position.x(),position.y())
def mouseReleaseEvent(self,e):
self.setSelected(False)
QtGui.QGraphicsPixmapItem.mouseReleaseEvent(self, e) // here calling the event
def mouseMoveEvent(self, e):
QtGui.QGraphicsPixmapItem.mouseMoveEvent(self, e)
class GfxScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
#build parent user interface
super(GfxScene, self).__init__(parent)
def mousePressEvent(self, e):
if(self.itemAt(e.scenePos().x(),e.scenePos().y()) == None):
pixmapItem = TestPixmapItem('test.png',e.scenePos())
self.addItem(pixmapItem)
else:
QtGui.QGraphicsScene.mousePressEvent(self,e);
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
scene = GfxScene(self)
scene.setSceneRect(QtCore.QRect(0, 0, 800, 800))
view = QtGui.QGraphicsView()
view.setScene(scene)
view.setSceneRect(scene.sceneRect())
#view.setGeometry(QtCore.QRect(0, 0, 800, 800))
self.setCentralWidget(view)
def main():
#This function means this was run directly, not called from another python file.
app = QtGui.QApplication.instance()
if app == None:
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()