PyQt5 using Drop_groupBox() from another file - drag-and-drop

I have a groupBox in my PyQt5-Application which serves as a dropzone, where the user can upload files and the dropEvent prints a list of the filenames that were dragged into the dropzone and writes them to the listWidget. I have slightly changed the original code from here:
dropfiles.py
# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
import os
from PyQt5 import QtCore, QtGui, QtWidgets
class Drop_groupBox(QtWidgets.QGroupBox):
dropped = QtCore.pyqtSignal(list)
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
list_of_files = [url.toLocalFile() for url in e.mimeData().urls() if os.path.isfile(url.toLocalFile())]
self.dropped.emit(list_of_files)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(658, 449)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(658, 449))
MainWindow.setMaximumSize(QtCore.QSize(658, 449))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_Files = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_Files.sizePolicy().hasHeightForWidth())
self.label_Files.setSizePolicy(sizePolicy)
self.label_Files.setMinimumSize(QtCore.QSize(122, 20))
self.label_Files.setMaximumSize(QtCore.QSize(122, 20))
self.label_Files.setObjectName("label_Files")
self.gridLayout.addWidget(self.label_Files, 0, 0, 1, 1)
self.listWidget_Files = QtWidgets.QListWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.listWidget_Files.sizePolicy().hasHeightForWidth())
self.listWidget_Files.setSizePolicy(sizePolicy)
self.listWidget_Files.setMinimumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setMaximumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setObjectName("listWidget_Files")
self.gridLayout.addWidget(self.listWidget_Files, 1, 0, 1, 1)
self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1)
# self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox = Drop_groupBox(self.centralwidget)
self.groupBox.dropped.connect(self.fill_fileslist)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(300, 300))
self.groupBox.setMaximumSize(QtCore.QSize(400, 300))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_3.addWidget(self.groupBox, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 658, 19))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "TestCase"))
self.label_Files.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">Selected Files</span></p></body></html>"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\">Drop Files Here!</span></p></body></html>"))
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
This works perfectly fine, when I have all the code in one file. But now my problem is that I am designing a gui with the PyQt Designer and I want to separate the "gui"-file from the file with the programming logic (programming functions), so that when I change something in the gui and convert it to a python file (with pyuic), the functions not defined in the Designer won't be overwritten. So this is what I have tried:
mainwindow.py (the gui file)
# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(658, 449)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(658, 449))
MainWindow.setMaximumSize(QtCore.QSize(658, 449))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_Files = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_Files.sizePolicy().hasHeightForWidth())
self.label_Files.setSizePolicy(sizePolicy)
self.label_Files.setMinimumSize(QtCore.QSize(122, 20))
self.label_Files.setMaximumSize(QtCore.QSize(122, 20))
self.label_Files.setObjectName("label_Files")
self.gridLayout.addWidget(self.label_Files, 0, 0, 1, 1)
self.listWidget_Files = QtWidgets.QListWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.listWidget_Files.sizePolicy().hasHeightForWidth())
self.listWidget_Files.setSizePolicy(sizePolicy)
self.listWidget_Files.setMinimumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setMaximumSize(QtCore.QSize(256, 341))
self.listWidget_Files.setObjectName("listWidget_Files")
self.gridLayout.addWidget(self.listWidget_Files, 1, 0, 1, 1)
self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(300, 300))
self.groupBox.setMaximumSize(QtCore.QSize(400, 300))
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_3.addWidget(self.groupBox, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 658, 19))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "TestCase"))
self.label_Files.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">Selected Files</span></p></body></html>"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\">Drop Files Here!</span></p></body></html>"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
dropfiles_functions.py (the file with the programming logic)
# -*- coding: utf-8 -*-
import os
from PyQt5 import QtCore, QtWidgets
from dropfiles_gui import Ui_MainWindow
class Drop_groupBox(QtWidgets.QGroupBox):
dropped = QtCore.pyqtSignal(list)
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
list_of_files = [url.toLocalFile() for url in e.mimeData().urls() if os.path.isfile(url.toLocalFile())]
self.dropped.emit(list_of_files)
class MConv(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.groupBox = Drop_groupBox(self.ui.centralwidget) # <-- why is this not working?
self.ui.groupBox.dropped.connect(self.fill_fileslist) # <-- why is this not working?
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MConv()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I don't understand why the drop event is not passed to the groupBox. In the file 'dropfiles_functions.py' I changed the 'self.ui.groupBox' to the 'new Drop_groupBox', but its funcitonaltiy is not working. Can someone please explain to me why this is the case and what I'm doing wrong?

In order to get this to work, you need to promote your groupbox widget in QtDesigner from a QtWidgets.QGroupBox to a Drop_groupBox widget. You can check the official Qt documentation to find out how. If you succeed and convert the .ui file to a .py file, the line
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
should have been replaced by
self.groupBox = Drop_groupBox(self.centralwidget)
and at the bottom of the .py file there should be an import statement similar to
from dropfiles_functions import Drop_groupBox
The next step is to correctly setup MConv. Since MConv inherits from both QMainWindow and Ui_MainWindow, you don't need to create a separate instance of Ui_MainWindow in QMainWindow.__init__. Instead you can refer to MConv.setupUi and MConv.groupBox directly, i.e.
class MConv(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__(self)
self.setupUi(self) # <-- this will define self.groupBox = Drop_groupbox(...) amongst others
self.groupBox.dropped.connect(self.fill_fileslist)
def fill_fileslist(self, files_list):
self.listWidget_Files.addItems(files_list)
print(files_list)
Finally, in the if __name__ == "__main__" block you need to make sure you are using an instance of MConv rather than a standard QMainWindow, i.e.
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MConv()
MainWindow.show()
sys.exit(app.exec_())

Related

Why does kivy keep freezing when using python sockets?

I'm working on a basic client-server desktop app project using kivy & sockets & threading.
The client & server work on it's own, however when I try to integrate it with kivy, python & kivy don't want to respond & yet no definitive error pops up.
Could i have some ideas as to how to fix this?
This is the code that freezes when i run it, if i take away the import server_sock it works as a general gui and doesnt freeze.
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import server_sock
import sys
kivy.require("2.1.0") #latest version
class ConnectPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text="IP:"))
self.ip = TextInput(multiline=False)
self.add_widget(self.ip)
self.add_widget(Label(text="PORT:"))
self.port = TextInput(multiline=False)
self.add_widget(self.port)
self.add_widget(Label(text="USERNAME:"))
self.user = TextInput(multiline=False)
self.add_widget(self.user)
self.join = Button(text="Join")
self.join.bind(on_press=self.join_button)
self.add_widget(Label())
self.add_widget(self.join)
def join_button(self, instance):
port = self.port.text
ip = self.ip.text
user = self.user.text
info = f"Attempting to join {ip}:{port} as {user}"
chat_app.info_page.update_info(info)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(self.connect,1)
def connect(self, _):
port = int(self.port.text)
ip = self.ip.text
user = self.user.text
try:
server_sock.connect(ip, port)
chat_app.create_chat_page()
chat_app.screen_manager.current = "Chat"
except:
show_error(message="not gonna happen")
class InfoPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.message = Label(halign="center", valign="middle", font_size="30")
self.message.bind(width=self.update_text_width)
self.add_widget(self.message)
def update_info(self,message):
self.message.text = message
def update_text_width(self, *_):
self.message.text_size = (self.message.width*0.9, None)
class ChatPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.add_widget(Label(text="Hey at least it works till now"))
class ChatApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.connect_page = ConnectPage()
screen = Screen(name="Connect")
screen.add_widget(self.connect_page)
self.screen_manager.add_widget(screen)
self.info_page = InfoPage()
screen= Screen(name="Info")
screen.add_widget(self.info_page)
self.screen_manager.add_widget(screen)
return self.screen_manager
def create_chat_page(self):
self.chat_page = ChatPage()
screen = Screen(name="Chat")
screen.add_widget(self.chat_page)
self.screen_manager.add_widget(screen)
def show_error(message):
chat_app.info_page.update_info(message)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(sys.exit, 10)
if __name__ == "__main__":
chat_app =ChatApp()
chat_app.run()
This is the server_sock file
import socket
import threading
import socket
HOST = '127.0.0.1'
PORT = 55555
server = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
try:
server.bind((HOST, PORT))
except:
print(f'unable to bind to {HOST} and {PORT}')
server.listen()
print(f"Listening for connections on {HOST}: {PORT}")
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def message_recv(client):
while True:
try:
message = client.recv(2048)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
nickname = nicknames[index]
broadcast(f'{nickname} left the chat'.encode('ascii'))
nicknames.remove(nickname)
break
def recieve():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send("SOMETHING".encode('ascii'))
nickname = client.recv(2048).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of the client is {nickname}")
broadcast(f"{nickname} joined the chat".encode('ascii'))
client.send("Connected to the server".encode('ascii'))
thread = threading.Thread(target=message_recv, args=(client,))
thread.start()
print("Server is listening")
recieve()

Cannot create a successful exe file in python [duplicate]

This question already has answers here:
'google-cloud-firestore' distribution doesn't get added to PyInstaller build
(3 answers)
Closed 3 years ago.
I am using a lot of dependencies for my python project. I am using firestore, pyqt5, numpy and some others. I tried creating an executable file using Pyinstaller but whenever I run the file it says "failed to execute script.
Also I am using images folder and 2 other python file as imports in my main.py file
I tried using hidden imports and still wouldn't work. Is there any easy way to create a pyqt5+firestore project?
Main.py
from PyQt5 import QtWidgets
from HomePage import Ui_HomePage
from attendance import Ui_Dialog
class Firstwindow(QtWidgets.QMainWindow, Ui_HomePage):
def __init__(self, parent=None):
super(Firstwindow, self).__init__(parent)
self.setupUi(self)
self.viewAttendance.clicked.connect(self.hide)
class Secondwindow(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Secondwindow, self).__init__(parent)
self.setupUi(self)
self.backButton.clicked.connect(self.hide)
class Manager:
def __init__(self):
self.first = Firstwindow()
self.second = Secondwindow()
self.first.viewAttendance.clicked.connect(self.second.show)
self.second.backButton.clicked.connect(self.first.show)
self.first.show()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
manager = Manager()
sys.exit(app.exec_())
attendance.py
from PyQt5 import QtCore, QtGui, QtWidgets
import firebase_admin
import google.cloud
from firebase_admin import credentials, firestore
cred = credentials.Certificate("******")
app1 = firebase_admin.initialize_app(cred)
"""Creating a database and authorization object"""
DB = firestore.client()
ids = []
names = []
age = []
job = []
phone = []
year = []
date = []
shiftStart = []
shiftEnd = []
store = firestore.client()
peopleRef = store.collection(u'People')
salaryRef = store.collection('Salary')
jobRef = store.collection('Jobs')
recordRef = store.collection('Records')
dates = recordRef.stream()
for dat in dates:
x = store.collection('Records').document(dat.id).collection('Present')
idx = x.stream()
for i in idx:
print(i.id)
print(i.to_dict()['Name'])
jo = jobRef.stream()
for doc in jo:
fo = doc.id
print(fo)
def getData():
try:
docs = peopleRef.stream()
for doc in docs:
ids.append(doc.id)
names.append(doc.to_dict()['Name'])
job.append(doc.to_dict()['Age'])
age.append(doc.to_dict()['Job Type'])
phone.append(doc.to_dict()['Phone'])
except google.cloud.exceptions.NotFound:
print(u'Missing data')
return ids,names,job,age,phone
def clearData():
ids.clear()
names.clear()
age.clear()
job.clear()
phone.clear()
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(595, 337)
Dialog.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False)
self.gridLayout_2 = QtWidgets.QGridLayout(Dialog)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 5, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem1, 0, 3, 1, 1)
self.dateEdit = QtWidgets.QDateEdit(Dialog)
self.dateEdit.setStyleSheet("font: 10pt \"Verdana\";")
self.dateEdit.setObjectName("dateEdit")
self.gridLayout.addWidget(self.dateEdit, 0, 6, 1, 1)
self.refreshButton = QtWidgets.QPushButton(Dialog)
self.refreshButton.setStyleSheet("qproperty-icon:url(:/images/icons/refresh.png);\n"
"background-color: rgb(255, 255, 255);")
self.refreshButton.setText("")
self.refreshButton.setIconSize(QtCore.QSize(20, 20))
self.refreshButton.setFlat(False)
self.refreshButton.setObjectName("refreshButton")
self.gridLayout.addWidget(self.refreshButton, 0, 4, 1, 1)
self.searchDate = QtWidgets.QPushButton(Dialog)
self.searchDate.setStyleSheet("QPushButton {\n"
" color: rgb(0,0,0);\n"
" border: 2px solid #555;\n"
" border-radius: 20px;\n"
" border-style: outset;\n"
" background: rgb(215, 252, 255);\n"
" padding: 5px;\n"
" font: 75 8pt \"Georgia\";\n"
" }\n"
"\n"
"QPushButton:hover {\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"\n"
"QPushButton:pressed {\n"
" border-style: inset;\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"")
self.searchDate.setObjectName("searchDate")
self.gridLayout.addWidget(self.searchDate, 0, 7, 1, 1)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.backButton = QtWidgets.QPushButton(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.backButton.sizePolicy().hasHeightForWidth())
self.backButton.setSizePolicy(sizePolicy)
self.backButton.setStyleSheet("qproperty-icon:url(:/images/icons/back.jpg);\n"
"background-color: rgb(255, 255, 255);")
self.backButton.setText("")
self.backButton.setObjectName("backButton")
self.horizontalLayout.addWidget(self.backButton)
self.nameEntry = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.nameEntry.sizePolicy().hasHeightForWidth())
self.nameEntry.setSizePolicy(sizePolicy)
self.nameEntry.setStyleSheet("font: 10pt \"Verdana\";")
self.nameEntry.setObjectName("nameEntry")
self.horizontalLayout.addWidget(self.nameEntry)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.searchName = QtWidgets.QPushButton(Dialog)
self.searchName.setStyleSheet("QPushButton {\n"
" color: rgb(0,0,0);\n"
" border: 2px solid #555;\n"
" border-radius: 20px;\n"
" border-style: outset;\n"
" background: rgb(215, 252, 255);\n"
" padding: 5px;\n"
" font: 75 8pt \"Georgia\";\n"
" }\n"
"\n"
"QPushButton:hover {\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"\n"
"QPushButton:pressed {\n"
" border-style: inset;\n"
" background: rgb(111, 210, 255)\n"
" }\n"
"")
self.searchName.setObjectName("searchName")
self.gridLayout.addWidget(self.searchName, 0, 1, 1, 1)
self.profileTree = QtWidgets.QTableWidget(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.profileTree.sizePolicy().hasHeightForWidth())
self.profileTree.setSizePolicy(sizePolicy)
self.profileTree.setObjectName("profileTree")
self.gridLayout.addWidget(self.profileTree, 1, 0, 1, 1)
self.dataTree = QtWidgets.QTableWidget(Dialog)
self.dataTree.setObjectName("dataTree")
self.gridLayout.addWidget(self.dataTree, 1, 1, 1, 7)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.dataTree.setColumnCount(0)
self.dataTree.setRowCount(0)
self.profileTree.setRowCount(0)
self.profileTree.setColumnCount(0)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.profileTree.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
self.refreshButton.clicked.connect(self.refresh)
self.profileTree.cellDoubleClicked.connect(self.showClicked)
def showClicked(self,row,col):
idx = self.profileTree.item(row,0).text()
print(idx)
def refresh(self):
profileData = getData()
self.profileTree.setRowCount(len(profileData[0]))
self.profileTree.setColumnCount(2)
self.profileTree.setHorizontalHeaderLabels(('ID', 'Name'))
for row in range(len(profileData[0])):
for col in range(2):
self.profileTree.setItem(row,col,QtWidgets.QTableWidgetItem(profileData[col][row]))
clearData()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.searchDate.setText(_translate("Dialog", "Search"))
self.searchName.setText(_translate("Dialog", "Search"))
import images
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
Ok so after hours of research I found this post - 'google-cloud-firestore' distribution doesn't get added to PyInstaller build
The problem was with firestore and not PyQt.

How to get filepath from droped file with pyqt5?

I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!
import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
size=100
imgNum=0
frameCount=4
isXmin = False
isXmax = False
isYmin = False
isYmax = False
isLeft= True
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
sizeObject = QDesktopWidget().screenGeometry()
# print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
self.xMax=sizeObject.width()-10
self.yMax=sizeObject.height()-10
print(self.xMax)
print(self.yMax)
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setStyleSheet("background-color:transparent;")
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
self.setAcceptDrops(True)
self.label=QLabel(self)
self.label.setAcceptDrops(True)
self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
for x in range(len(self.pixmaps)):
self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
self.changeTimer=QTimer(self)
self.changeTimer.timeout.connect(self.changeFoot)
self.moveTimer=QTimer(self)
self.moveTimer.timeout.connect(self.moving)
self.setAcceptDrops(True)
pygame.init()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
self.show()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
def moving(self):
if self.distance == 0:
print(self.distance)
print(self.x(),"x",self.y())
self.label.setPixmap(self.pixmaps[1])
self.moveTimer.stop()
self.changeTimer.stop()
time.sleep(3)
self.setMovement()
return 0
else:
self.move(self.x()+self.direct[0],self.y()+self.direct[1])
self.distance-=1
if self.x()<=-10 :
self.distance=0
print("xm")
self.isXmin = True
if self.y()<=-10 :
self.distance=0
print("ym")
self.isYmin = True
if self.x()>=self.xMax:
self.distance=0
print("xM")
self.isXmax=True
if self.y()>=self.yMax :
self.distance=0
print("yM")
self.isYmax=True
def setMovement(self):
self.direct=[0,0]
while(self.direct[0]==0 and self.direct[1]==0):
self.direct=[random.randint(-1,1),random.randint(-1,1)]
if self.isXmax:
self.direct[0]=-1
if self.isXmin:
self.direct[0]=1
if self.isYmin:
self.direct[1]=1
if self.isYmax:
self.direct[1]=-1
if self.direct[0]== -1:
self.isLeft=True
self.imgNum=0
elif self.direct[0]== 1:
self.isLeft=False
self.imgNum=4
self.isXmax = False
self.isXmin = False
self.isYmin = False
self.isYmax = False
# if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
# else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
self.distance=random.randint(200,400)
self.changeTimer.start(300)
self.moveTimer.start(30)
def changeFoot(self):
self.label.setPixmap(self.pixmaps[self.imgNum])
if self.isLeft:
if self.imgNum<self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=0
else:
if self.imgNum<2*self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=self.frameCount
def mousePressEvent(self, QMouseEvent):
self.setMovement()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
sys.exit()
# if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
i set AcceptDrops(True)
self.setAcceptDrops(True)
and code about get filepath ▼
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
Try to loop through event.mimeData().urls()
for url in event.mimeData().urls():
self.path = url.toLocalFile()

How do I update widgets in the window and add new widgets to the window in PyGObject?

I have a window set up with a few widgets but I want those widgets' information to be updated after some user input (e.g. button click). Also, I want an event handler to be able to add a new widget to the window.
I have attached an attempt at the below simple version of my question. Obviously it does not work though.
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, Gtk
class Button(Gtk.Box):
def __init__(self, message, label, window_grid):
Gtk.Box.__init__(self, spacing=6)
self.set_border_width(10)
self.label = label
self.window_grid = window_grid
button = Gtk.Button.new_with_label(message)
button.connect("clicked", self.on_click)
self.pack_start(button, True, True, 0)
def on_click(self, widget):
# Change/update a label in the window_grid
self.label = LabelBox("Changed the label")
self.label.queue_draw()
# Add a new label to the window_grid
new_label = LabelBox("New label")
self.window_grid.attach(new_label, 0, 2, 1, 1)
class LabelBox(Gtk.Box):
def __init__(self, message):
Gtk.Box.__init__(self, spacing=6)
self.set_border_width(10)
label = Gtk.Label(message)
self.pack_start(label, True, True, 0)
win = Gtk.Window()
window_grid = Gtk.Grid()
label = LabelBox("This is a label")
button = Button("Test", label, window_grid)
window_grid.attach(label, 0, 0, 1, 1)
window_grid.attach(button, 0, 1, 2, 2)
win.add(window_grid)
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
Your code structure is poorly formatted. This code worked for me:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
import sys
class GUI:
def __init__(self):
self.win = Gtk.Window()
self.window_grid = Gtk.Grid()
box = Gtk.Box()
button = Gtk.Button.new_with_label("Test")
button.connect("clicked", self.on_click)
self.label = Gtk.Label("This is a label")
self.window_grid.attach(self.label, 0, 0, 1, 1)
self.window_grid.attach(button, 0, 1, 2, 2)
self.win.add(self.window_grid)
self.win.connect("delete-event", Gtk.main_quit)
self.win.show_all()
def on_click(self, widget):
# Change/update a label in the window_grid
self.label.set_label('Label changed')
label = Gtk.Label("Another label")
self.window_grid.attach(label, 2, 1, 2, 2)
self.win.show_all()
def main():
app = GUI()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())
Also keep #andlabs comment in mind, widgets are hidden by default.
As already said, your code logic ain't good. You must try to understand how to design your applications. Anyway, I've managed to get your code working to fit your question:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class Button(Gtk.Box):
def __init__(self, message, label, window_grid):
Gtk.Box.__init__(self, spacing=6)
self.set_border_width(10)
self.label = label
self.window_grid = window_grid
button = Gtk.Button.new_with_label(message)
button.connect("clicked", self.on_click)
self.pack_start(button, True, True, 0)
def on_click(self, widget):
# Change/update a label in the window_grid
self.label.label.set_text("Changed the lable")
# Add a new label to the window_grid
new_label = LabelBox("New label")
self.window_grid.attach(new_label, 0, 2, 1, 1)
new_label.show_all()
class LabelBox(Gtk.Box):
def __init__(self, message):
Gtk.Box.__init__(self, spacing=6)
self.set_border_width(10)
self.label = Gtk.Label(message)
self.pack_start(self.label, True, True, 0)
win = Gtk.Window()
window_grid = Gtk.Grid()
label = LabelBox("This is a label")
button = Button("Test", label, window_grid)
window_grid.attach(label, 0, 0, 1, 1)
window_grid.attach(button, 0, 1, 1, 1)
win.add(window_grid)
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
Compare it to yours to see the mistakes you've made. There was no need to wrap the label and the button inside GtkBox.

NameError: global name 'Carnage' is not defined

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.