无法调整QTableWidget的大小

时间:2018-07-03 07:54:51

标签: python pyqt pyqt5 qlayout

我正在尝试调整QVBoxlayout中的表格小部件的大小,然后将其作为一行添加到pyqt中的QFormlayout

我目前正在添加一个QVboxlayout,其中包含一个表格小部件,作为Qformlayout中的一行。

主要目的是整理Table小部件,直到应用程序窗口结束为止,它获取窗口上的剩余空间

使用以下代码-

class PGSearchDetails():

    def __init__(self,parent=None):

         self.widget_pgsd = QWidget()
         self.layout_pgsd = QFormLayout()
         self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
         self.PG_Id = QLineEdit()
         #rx = QRegExp("^\\D+[!,@,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
         #rx = QRegExp(" (?!(@,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
         str_rx = QRegExp("^[A-Za-z*]{20}(?!@#$%^&*():\"\{\}?<>\|+-~!_-)")
         adhr_rx = QRegExp("[A-Z0-9]{12}(?!@#$%^&*():\"\{\}?<>\|+-~!_)")

         val = QRegExpValidator(str_rx)
         val3 = QRegExpValidator(adhr_rx)

         self.PG_Id.setValidator(val3)
         self.LastName = QLineEdit()
         self.LastName.setValidator(val)
         self.MobNum = QLineEdit()
         qint_val = QIntValidator()
         qint_val.setTop(10)
         self.MobNum.setValidator(qint_val)


         self.layout_pgsd.addRow("First Name",self.PG_Id)
         self.layout_pgsd.addRow("Last Name",self.LastName)
         self.layout_pgsd.addRow("Mobile Number",self.MobNum)

         update_layout_pgsd = QHBoxLayout()

         layout_test,table = dbv.Search_View(self.getT)

         #layout_test.setGeometry(QRect(200,200,50,50))

         #table.setMaximumHeight(800)
         #table.setGeometry(200,200,200,200)
         #table.setGeometry(1,1,1000,600)
         table.resize(1000,600)

         update_btn_pgsd = QPushButton('Update')
         reset_btn_pgsd = QPushButton('Reset')

         update_layout_pgsd.addWidget(update_btn_pgsd)
         update_layout_pgsd.addWidget(reset_btn_pgsd)

         self.layout_pgsd.addRow(update_layout_pgsd)

         ##Adding the Table Widget to FormLayot
         self.layout_pgsd.addRow(layout_test)
         update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
                                                         self.LastName))
         #self.widget.setLayout(self.layout_pgsd)


    def returnLayout(self):
        return self.layout_pgsd

    def returnWidget(self):
        return self.widget_pgsd

    def getT(self,linedit):
        print("LE--->",linedit.text())

QtableWidget设置---

def Search_View(self):

    print("Inside Search_view")


    central_widget = QWidget()              # Create a central widget
    db_layout = QVBoxLayout()
    #col_count = len(self.pg_details.__dict__.keys())
    col_count = 3

    table = QTableWidget()  # Create a table
    #central_widget.setGeometry(200,200,150,150)
    #table.maximumSize()
    #db_layout.setMaximumSize(200)
    db_layout.setGeometry(QRect(0,0,100,30))


    db_layout.addWidget(table)


    ##Tried resizing the Table widget but nothing seems to works
    table.resize(1000,600)
    table.setGeometry(0,2,1000,600)

    #central_widget.resize(central_widget.sizeHint())

    #central_widget.setColumnWidth(1000,600)

    #db_layout.addItem(update_layout)

    central_widget.setLayout(db_layout)

    print("Geometry  H--->",table.geometry().height())
    print("Geometry  W--->",table.geometry().width())
    print("Geometry  X--->",table.geometry().x())
    print("Geometry  Y--->",table.geometry().y())



    return central_widget,table

调整大小功能后,表格的几何形状更改为1000,600,但在屏幕上未反映出来。在应用程序屏幕上,每次都保持相同大小

还找到了完整的代码,其中还包含Tablayouts和单个单选按钮的Stacked小部件

class MainWindow(QMainWindow):

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

    def init_ui(self):
        self.tab_widget = MainTabWindow()
        self.setCentralWidget(self.tab_widget)
        self.show()



class MainTabWindow(QTabWidget):

    def __init__(self,parent=None):
        super(MainTabWindow, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('PyQt5 Tab Example')

        self.tab1 = QWidget()

        self.addTab(self.tab1,"Search")


        self.PGSearchTab()


    def PGSearchTab(self):
      print("Search Tab First Tab")
      self.central_layout = QVBoxLayout()

      self.stack1 = QWidget()
      self.stack2 = QWidget()
      self.stack3 = QWidget()

      self.stack_widget = QStackedWidget()

      button_layout = QHBoxLayout()
      radio_button_1 = QRadioButton("Search")
      radio_button_2 = QRadioButton("Add")
      radio_button_3 = QRadioButton("Update")

      button_layout.addWidget(radio_button_1)
      button_layout.addWidget(radio_button_2)
      button_layout.addWidget(radio_button_3)

      self.central_layout.addItem(button_layout)

      self.stack_widget.addWidget(self.stack1)
      self.stack_widget.addWidget(self.stack2)
      self.stack_widget.addWidget(self.stack3)


      self.central_layout.addWidget(self.stack_widget)

      radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))

      self.setTabText(0,"Search")

      update_layout = QHBoxLayout()

      update_layout.setAlignment(QtCore.Qt.AlignBottom)
      update_btn = QPushButton('Update')
      reset_btn = QPushButton('Reset')


      update_layout.addWidget(update_btn)
      update_layout.addWidget(reset_btn)

      self.tab1.setLayout(self.central_layout)


    def SelectButtonCheck(self,b):
        if b.text() == "Search":
            if b.isChecked():
                print(b.text()+ "is selected")
                self.obj_pgsd = pgsd.PGSearchDetails()
                layout = self.obj_pgsd.returnLayout()
                if self.stack1.layout() is None:
                    self.stack1.setLayout(layout)

                self.stack_widget.setCurrentIndex(0)


def main():

    application = QApplication(sys.argv)
    main_window = MainTabWindow()
    main_window.show()
    sys.exit(application.exec_())

if __name__ == '__main__':
    main()

我似乎不明白我在这里想念什么

任何指针将不胜感激。

还要找到执行上述布局设置所需的工作代码。

#!/usr/local/bin/python3

import sys
from PyQt5.QtWidgets import (QApplication, QWidget,QMainWindow,QLineEdit,QAction,
                            QLabel,QPushButton,QVBoxLayout,
                            QTabWidget,QFormLayout,QHBoxLayout,
                            QRadioButton,QCheckBox,QTextEdit,
                            QListView,QDialogButtonBox,QSizePolicy,QCalendarWidget)
from PyQt5 import QtCore
import PyQt5.Qt
from PyQt5.Qt import *
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtSql
from functools import partial


class MainWindow(QMainWindow):

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

    def init_ui(self):
        self.tab_widget = MainTabWindow()
        self.setCentralWidget(self.tab_widget)
        self.show()



class MainTabWindow(QTabWidget):

    def __init__(self,parent=None):
        super(MainTabWindow, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('PyQt5 Tab Example')

        self.tab1 = QWidget()

        self.addTab(self.tab1,"Search")


        self.PGSearchTab()


    def PGSearchTab(self):
      print("Search Tab First Tab")
      self.central_layout = QVBoxLayout()

      self.stack1 = QWidget()
      self.stack2 = QWidget()
      self.stack3 = QWidget()

      self.stack_widget = QStackedWidget()

      button_layout = QHBoxLayout()
      radio_button_1 = QRadioButton("Search")
      radio_button_2 = QRadioButton("Add")
      radio_button_3 = QRadioButton("Update")

      button_layout.addWidget(radio_button_1)
      button_layout.addWidget(radio_button_2)
      button_layout.addWidget(radio_button_3)

      self.central_layout.addItem(button_layout)

      self.stack_widget.addWidget(self.stack1)
      self.stack_widget.addWidget(self.stack2)
      self.stack_widget.addWidget(self.stack3)


      self.central_layout.addWidget(self.stack_widget)

      radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))

      self.setTabText(0,"Search")

      update_layout = QHBoxLayout()

      update_layout.setAlignment(QtCore.Qt.AlignBottom)
      update_btn = QPushButton('Update')
      reset_btn = QPushButton('Reset')


      update_layout.addWidget(update_btn)
      update_layout.addWidget(reset_btn)

      self.tab1.setLayout(self.central_layout)


    def SelectButtonCheck(self,b):
        if b.text() == "Search":
            if b.isChecked():
                print(b.text()+ "is selected")
                self.obj_pgsd = PGSearchDetails()
                layout = self.obj_pgsd.returnLayout()
                if self.stack1.layout() is None:
                    self.stack1.setLayout(layout)

                self.stack_widget.setCurrentIndex(0)


class PGSearchDetails():

    def __init__(self,parent=None):

         self.widget_pgsd = QWidget()
         self.layout_pgsd = QFormLayout()
         self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
         self.PG_Id = QLineEdit()
         #rx = QRegExp("^\\D+[!,@,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
         #rx = QRegExp(" (?!(@,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
         str_rx = QRegExp("^[A-Za-z*]{20}(?!@#$%^&*():\"\{\}?<>\|+-~!_-)")
         adhr_rx = QRegExp("[A-Z0-9]{12}(?!@#$%^&*():\"\{\}?<>\|+-~!_)")

         val = QRegExpValidator(str_rx)
         val3 = QRegExpValidator(adhr_rx)

         self.PG_Id.setValidator(val3)
         self.LastName = QLineEdit()
         self.LastName.setValidator(val)
         self.MobNum = QLineEdit()
         qint_val = QIntValidator()
         qint_val.setTop(10)
         self.MobNum.setValidator(qint_val)


         self.layout_pgsd.addRow("First Name",self.PG_Id)
         self.layout_pgsd.addRow("Last Name",self.LastName)
         self.layout_pgsd.addRow("Mobile Number",self.MobNum)

         update_layout_pgsd = QHBoxLayout()

         layout_test,table = self.Search_View(self.getT)

         #layout_test.setGeometry(QRect(200,200,50,50))

         #table.setMaximumHeight(800)
         #table.setGeometry(200,200,200,200)
         #table.setGeometry(1,1,1000,600)
         table.resize(1000,600)

         update_btn_pgsd = QPushButton('Update')
         reset_btn_pgsd = QPushButton('Reset')

         update_layout_pgsd.addWidget(update_btn_pgsd)
         update_layout_pgsd.addWidget(reset_btn_pgsd)

         self.layout_pgsd.addRow(update_layout_pgsd)

         ##Adding the Table Widget to FormLayot
         self.layout_pgsd.addRow(layout_test)
         update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
                                                         self.LastName))
         #self.widget.setLayout(self.layout_pgsd)


    def returnLayout(self):
        return self.layout_pgsd

    def returnWidget(self):
        return self.widget_pgsd

    def getT(self,linedit):
        print("LE--->",linedit.text())

    def Search_View(self,text):

        print("Inside Search_view")


        central_widget = QWidget()              # Create a central widget
        db_layout = QVBoxLayout()
        #col_count = len(self.pg_details.__dict__.keys())
        col_count = 3

        table = QTableWidget()  # Create a table
        #central_widget.setGeometry(200,200,150,150)
        #table.maximumSize()
        #db_layout.setMaximumSize(200)
        db_layout.setGeometry(QRect(0,0,100,30))


        db_layout.addWidget(table)


        ##Tried resizing the Table widget but nothing seems to works
        table.resize(1000,600)
        table.setGeometry(0,2,1000,600)

        #central_widget.resize(central_widget.sizeHint())

        #central_widget.setColumnWidth(1000,600)

        #db_layout.addItem(update_layout)

        central_widget.setLayout(db_layout)

        print("Geometry  H--->",table.geometry().height())
        print("Geometry  W--->",table.geometry().width())
        print("Geometry  X--->",table.geometry().x())
        print("Geometry  Y--->",table.geometry().y())



        return central_widget,table

    def SqlExec(self,text):
        db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
        db.setHostName('localhost')
        db.setDatabaseName('Test')
        db.setUserName('root')
        db.open()

        query = QtSql.QSqlQuery()
        select = "select * from Test.PG_Details where PG_Id=?"# where PG_Id = 1"
        query.prepare(select)
        indexes = range(3)
        print("TEXT----->",text)
        query.addBindValue(text)
        #query.exec_(select)
        query.exec_()

        print("Sizze----",query.size())
        row_count = query.size()
        db.record('PG_Details')

        col_list = []

        for i in range(db.record('PG_Details').count()):
            print("FIELD----->",db.record('PG_Details').field(i).name())
            col_list.append(db.record('PG_Details').field(i).name())

        db.close()

        return query,row_count,col_list


    def database(self,table,text,text2):

        text = text.text()
        query_result,row_count,col_list = self.SqlExec(text)

        i = 0
        table.setColumnCount(3)     #Set three columns
        table.setRowCount(row_count)
        table.setHorizontalHeaderLabels(col_list)
        while query_result.next():
            #print(query_result.value(i))
            result_row = [query_result.value(index) for index in range(query_result.record().count())]
            #print("RR--->",result_row)
            for idx,val in enumerate(result_row):
                #print("IDX----->",idx)
                table.setItem(i, idx, QTableWidgetItem(val))
            i = i + 1



def main():

    application = QApplication(sys.argv)
    main_window = MainTabWindow()
    main_window.show()
    sys.exit(application.exec_())

if __name__ == '__main__':
    main()

enter image description here

1 个答案:

答案 0 :(得分:1)

问题在于,每次使用addRow()添加小部件时,QFormLayout都会使用strech,解决方案是使用QVBoxLayout,并且QVBoxLayout会传递QFormLayout和layout_test。

class PGSearchDetails():
    def __init__(self,parent=None):

         self.widget_pgsd = QWidget()
         self.layout = QVBoxLayout() # <---
         self.layout_pgsd = QFormLayout()
         self.layout.addLayout(self.layout_pgsd) # <---
         self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
         ...

         self.layout_pgsd.addRow(update_layout_pgsd)

         ##Adding the Table Widget to FormLayot
         # self.layout_pgsd.addRow(layout_test)
         self.layout.addWidget(layout_test) # <---
         update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
                                                         self.LastName))


    def returnLayout(self):
        return self.layout # <---

enter image description here