简体   繁体   English

pyqt5 组合框选定的项目与另一个窗口共享(信号/插槽)

[英]pyqt5 combobox selected item share with another window (signal/slot)

I am trying to get Qcombobox selected variable data from onewindow.py to anotherWindow.py.我正在尝试将 Qcombobox 选定的变量数据从 onewindow.py 获取到 anotherWindow.py。 i am stuck when i use signal/slot mechanism.当我使用信号/插槽机制时,我被卡住了。

i have two files mainWindow.py and connection.py , in mainWindow i have a combobox where user can choose a server, i want, when user choose a server from combobox then then selected item(variable) will be sent to the connection.py我有两个文件mainWindow.pyconnection.py ,在 mainWindow 我有一个组合框,用户可以在其中选择一个服务器,我想要,当用户从组合框中选择一个服务器时,然后选定的项目(变量)将被发送到 connection.py

mainwindow.py:主窗口.py:

from PyQt5 import QtCore, QtGui, QtWidgets


class ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(310, 230, 151, 22))
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(310, 300, 281, 20))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # combobox selected
        self.comboBox.activated[str].connect(self.onChanged)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.comboBox.setItemText(0, _translate("MainWindow", "TFUS3"))
        self.comboBox.setItemText(1, _translate("MainWindow", "TFUSD"))
        self.label.setText(_translate("MainWindow", "TextLabel"))

    #-----------
    def onChanged(self,text):
        self.label.setText(text)
        message=text
        return message

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_())

and connection.py连接.py

 from PyQt5 import QtCore, QtGui, QtWidgets
    from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
    from PyQt5.QtWidgets import QTableView, QApplication
    import mainWindow
    from mainWindow import *

    class Example(QWidget):

        def get_value(self,text):
        message=text
        print(message)

        def __init__(self):
            super().__init__()

            self.initUI()

        def initUI(self):      

            self.lbl = QLabel("select server from mainwindow is:",self )

            self.setGeometry(300, 300, 300, 200)
            self.setWindowTitle('QComboBox')
            self.show()


        def onActivated(self, text):


            createConnection(self,text)
            self.lbl.adjustSize()  


    ------server part----------------------------
    USERNAME = 'XXXXXX'
    PASSWORD = '000000'

    def selectedServer(server):
        switcher ={
            'Server1': 'x.x.x.x,1433',
            'Server2': 'x.x.x.x,1433',
        }
        return switcher.get(server,"Invalid Server ")

    def createConnection(self,server):


        SERVER= selectedServer(server)

        global db
        db = QSqlDatabase.addDatabase('QODBC')
        db.setDatabaseName(f'Driver={{SQL SERVER}}; Server={SERVER}; UID={USERNAME}; PWD={PASSWORD}')
        if db.open():
            self.lbl.setText(f'{server} Server connected successfully')
            print(f'{server} Server connected successfully')

        else:
            print('connection failed')


    if __name__ == '__main__':

        app = QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())

i tried many time to show selected server in textlabe in connection window.but failed.我尝试了很多次在连接窗口的文本标签中显示选定的服务器。但失败了。 don't know where i did mistake.不知道我哪里做错了。

First of all it must be clear that information is not sent between files but between objects, the application is not the files but the interaction between the objects or other elements that are described in the source code(files).首先必须清楚,信息不是在文件之间发送而是在对象之间发送,应用程序不是文件,而是源代码(文件)中描述的对象或其他元素之间的交互。

On the other hand you should not modify the code generated by Qt Designer so you will have to restore the mainWindow.py file.另一方面,您不应修改 Qt Designer 生成的代码,因此您必须恢复 mainWindow.py 文件。

Considering the above, an instance of each class must be created (in the case of Ui_MainWindow it is better to create a new class that inherits from the appropriate widget and use Ui_MainWindow to fill it).考虑到上述情况,必须创建每个类的实例(在 Ui_MainWindow 的情况下,最好创建一个继承自适当小部件的新类并使用 Ui_MainWindow 来填充它)。 And then there make the connection between the components.然后在组件之间建立连接。

connection.py连接.py

import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql


USERNAME = "XXXXXX"
PASSWORD = "000000"


def selectedServer(server):
    switcher = {
        "Server1": "x.x.x.x,1433",
        "Server2": "x.x.x.x,1433",
    }
    return switcher.get(server, "Invalid Server ")


class Example(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.lbl = QtWidgets.QLabel("select server from mainwindow is:", self)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle("QComboBox")

    def setServer(self, name):
        self.createConnection(name)
        self.lbl.adjustSize()

    def createConnection(self, server):
        SERVER = selectedServer(server)
        db = QtSql.QSqlDatabase.addDatabase("QODBC")
        db.setDatabaseName(
            f"Driver={{SQL SERVER}}; Server={SERVER}; UID={USERNAME}; PWD={PASSWORD}"
        )
        if db.open():
            self.lbl.setText(f"{server} Server connected successfully")
            self.lbl.adjustSize()
            print(f"{server} Server connected successfully")

        else:
            print("connection failed")


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

main.py主文件

import sys

from PyQt5 import QtWidgets

from mainWindow import ui_MainWindow
from connection import Example


class MainWindow(QtWidgets.QMainWindow, ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    ex = Example()
    ex.show()

    w.comboBox.currentTextChanged.connect(ex.setServer)
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM